-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmfc.c
70 lines (59 loc) · 2.1 KB
/
mfc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//
// mfc.c
// mfc
//
// Created by Vlad Mihaylenko on 27/01/15.
// Copyright (c) 2015 Vlad Mihaylenko. All rights reserved.
//
#include "mfc.h"
#define kCharCount 256
#define kThreadCount 2
void* most_freq_char_countChars(void* args) {
CountCharArgs_t* arg = (CountCharArgs_t*)args;
CountRecord_t *commonCountRecord = arg->commonCountArray;
char* charSubArray = arg->charSubArray;
__builtin_prefetch(charSubArray);
int charSubArrayLength = arg->charSubbArrayLength;
for (int i = 0; i < charSubArrayLength; i++) {
char scannedChar = charSubArray[i];
CountRecord_t* record = commonCountRecord + scannedChar;
if (mfc_try_lock(&record->mutex)) {
record->count++;
mfc_unlock(&record->mutex);
}
}
return NULL;
}
char mostFrequentCharacter(char* str, int size) {
assert(size>0);
if (size == 1)
return *str;
CountRecord_t countRecords[kCharCount] = {{0, 0}};
CountCharArgs_t args[kThreadCount];
for (int i = 0; i < kThreadCount; i++)
args[i].commonCountArray = countRecords;
const int blockSize = size / kThreadCount;
for (int i = 0; i < kThreadCount - 1; i++) {
char* charPosition = (str + i * blockSize);
args[i].charSubArray = charPosition;
args[i].charSubbArrayLength = blockSize;
}
int lastPartIndex = (kThreadCount - 1) * blockSize;
args[kThreadCount - 1].charSubArray = str + lastPartIndex;
args[kThreadCount - 1].charSubbArrayLength = size - lastPartIndex;
pthread_t count_chars_thread[kThreadCount - 1];
for (int i = 0; i < kThreadCount - 1; i++) {
pthread_create(&count_chars_thread[i], NULL, most_freq_char_countChars, &args[i]);
}
most_freq_char_countChars(&args[kThreadCount - 1]);
for (int i = 0; i < kThreadCount; i++)
pthread_join(count_chars_thread[i], NULL);
char result = 0;
count_record_count_t max = 0;
for (int i = 0; i < kCharCount; i++)
if (countRecords[i].count > max) {
max = countRecords[i].count;
result = i;
}
return result;
}