-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordsCounter-v3.cpp
367 lines (330 loc) · 9.16 KB
/
WordsCounter-v3.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*********************************************************
* Author: Pihai Sun *
* University: Qingdao University *
* College: College of Computer Science and Technology *
*********************************************************/
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <thread>
#include <pthread.h>
#include <cstring>
#include <queue>
#include <vector>
#include <fstream>
#include <sstream>
#include <atomic>
#include <iomanip>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef unordered_map<string, int> WordMap;
typedef vector<string> StrVec;
typedef queue<string> StrQueue;
typedef priority_queue<pair<int, string>> StrNum;
/**
* @staResult: The mapping of words to their numbers
* @WorkQueue: Hold the lines to be worked on by programs
* @pathQueue: The path of the file need to be counted
* @wordsRank: Sort by number of word occurrences
* @maxQSize: Maximum number of lines in work queue
* @queStock: Number of string lines in the work queue
* @printNum: Output 'printNum' words that appear the most
*/
WordMap staResult;
StrQueue workQueue, pathQueue;
StrNum wordsRank;
atomic<int> producerNum = ATOMIC_VAR_INIT(0);
const size_t maxQSize = 10000;
const int printNum = 10;
const std::string instruct =
"Please entire the path of directory or path, or type exit to quit";
/**
* @pathMutex: Mutex for pathQueue
* @queueMutex: Mutually exclusive access to the work queue
* @mutexMap: Mutex for staResult
* @condQueue: condition variavle for workQueue -- avoid spin lock
*/
pthread_mutex_t pathMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t queueMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexMap = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condQueue = PTHREAD_COND_INITIALIZER;
/**
* Get all txt files under the given path
* @param path
* @param pathQueue
*/
void getFiles(string path)
{
struct stat fSta;
stat(path.c_str(), &fSta);
if (S_ISDIR(fSta.st_mode))
{
DIR *pDir = opendir(path.c_str());
struct dirent *ptr = NULL;
// Access the files in this directory in turn
while ((ptr = readdir(pDir)) != 0)
{
// Recursively enter subfolders
// ! Must judge whether the file name starts with '.'
if (ptr->d_type == DT_DIR && ptr->d_name[0] != '.')
{
getFiles(path + "/" + ptr->d_name);
continue;
}
string fName = ptr->d_name;
// Only fetch files of TXT type
if (fName.find(".txt") != string::npos)
{
pathQueue.push(path + "/" + ptr->d_name);
}
}
closedir(pDir);
}
else if (S_ISREG(fSta.st_mode) && path.find(".txt") != string::npos)
{
// The path is a TXT file
pathQueue.push(path);
}
else
{
puts("Invalid path or no TXT file under the path!\n");
}
}
/**
* return true if pathQueue is empty
*/
bool isEmptyPath()
{
bool res;
pthread_mutex_lock(&pathMutex);
res = pathQueue.empty();
pthread_mutex_unlock(&pathMutex);
return res;
}
/**
* Read the file in and add each line to the work queue for the producer
* @param fp The file path
*/
void producer(const string fp)
{
ifstream fileStream(fp);
string line;
while (getline(fileStream, line))
{
pthread_mutex_lock(&queueMutex);
while (workQueue.size() >= maxQSize)
{
// Waiting for the work queue is not full
pthread_cond_wait(&condQueue, &queueMutex);
}
// Add the line to end of work queue
workQueue.push(line);
// Wake up a waiting thread
pthread_cond_signal(&condQueue);
pthread_mutex_unlock(&queueMutex);
}
}
/**
* Send the file path in pathQueue to the producer
* @param pathQueue
*/
void *launchProducer(void *args)
{
producerNum++;
string fp;
while (!isEmptyPath())
{
// ! Use trylock instead of lock to avoid blocking forever
int getLockStu = pthread_mutex_trylock(&pathMutex);
if (getLockStu != 0)
{
// Didn't get the lock
continue;
}
fp = pathQueue.front();
pathQueue.pop();
pthread_mutex_unlock(&pathMutex);
producer(fp);
}
producerNum--;
return NULL;
}
/**
* Convert punctuation in a line into spaces
* @param: line
* @return: A line of characters without punctuation
*/
string cleanPunct(const string &line)
{
string str = line;
replace_if(str.begin(), str.end(), ::ispunct, ' ');
return str;
}
/**
* Make a word lowercase
* @param word
* @return A lowercased word
*/
void toLowerCase(string &str)
{
transform(str.begin(), str.end(), str.begin(), ::tolower);
}
/**
* return true if work queue is empty
*/
bool isEmptyWork()
{
bool res;
pthread_mutex_lock(&queueMutex);
res = workQueue.empty();
pthread_mutex_unlock(&queueMutex);
return res;
}
/**
* Count the words in this line
* @param staResult
* @param line
* ! Can not pass reference type parameters to the function,
* ! because the 'line' will be modified in the consumer
*/
void wordCount(string line)
{
cleanPunct(line);
istringstream is(line);
string word;
while (is >> word)
{
toLowerCase(word);
// Exclusive access to staREsult
pthread_mutex_lock(&mutexMap);
staResult[word]++;
pthread_mutex_unlock(&mutexMap);
}
}
/**
* Take out the string stored in the work queue by the producer
* and send it to the Counter function
*/
void *consumer(void *args)
{
string line;
// loop while producer is working or queue is not empty
while (producerNum > 0 || !isEmptyWork())
{
pthread_mutex_lock(&queueMutex);
while (producerNum > 0 && workQueue.empty())
{
// Wait for the producer to stop reading or the work queue is not empty
pthread_cond_wait(&condQueue, &queueMutex);
}
if (!workQueue.empty())
{
// Only take strings when the work queue is not empty
line = workQueue.front();
workQueue.pop();
}
pthread_cond_signal(&condQueue); // Wake up a waiting thread
pthread_mutex_unlock(&queueMutex);
// Count words in this line
wordCount(line);
}
return NULL;
}
/**
* Sort the word frequency in staResult in descending order
* @param staResult
* @param wordsRank
*/
void sortWords()
{
auto iter = staResult.begin();
while (iter != staResult.end())
{
wordsRank.push(make_pair(iter->second, iter->first));
iter++;
}
}
/**
* Output the 'printNum' most frequent words
* @param wordsRank
* @param printNum
*/
void printHotWords()
{
// Print title
printf("%-10s%-20s%-10s\n", "RANK", "KEY WORDS", "FREQUENCY");
for (int i = 1; i <= printNum && !wordsRank.empty(); i++)
{
cout << setiosflags(ios::left)
<< setw(10) << i << setw(20) << wordsRank.top().second
<< setw(10) << wordsRank.top().first << endl;
wordsRank.pop();
}
}
/**
* Launch all the threads needed
* @param threadGroup
* @param fp
* @param threadGroup
* @param threads
*/
void threadLauncher(std::vector<pthread_t *> &threadGroup, int cores, string &path)
{
getFiles(path);
for (int i = 0; i < cores / 2; i++)
{
threadGroup.push_back(new pthread_t);
pthread_create(threadGroup[i], NULL, launchProducer, NULL);
}
for (int i = cores / 2; i < cores; i++)
{
threadGroup.push_back(new pthread_t);
pthread_create(threadGroup[i], NULL, consumer, NULL);
}
for (int i = 0; i < threadGroup.size(); i++)
{
pthread_join(*threadGroup[i], NULL);
free(threadGroup[i]);
threadGroup[i] = NULL;
}
sortWords();
printHotWords();
}
/**
* Initialize variables
*/
void initVariable()
{
staResult.clear();
while (!wordsRank.empty())
wordsRank.pop();
}
int main()
{
size_t cores = std::thread::hardware_concurrency();
cout << cores << " concurrent threads are supported.\n";
string path;
cout << instruct << endl;
while (cin >> path)
{
if (path == "exit" || path == "quit")
{
return 0;
}
auto start = high_resolution_clock::now();
// launch threads to process
std::vector<pthread_t *> threadGroup;
threadLauncher(threadGroup, cores, path);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
cout << "Time taken by function: "
<< duration.count() << " milliseconds" << endl;
cout << endl
<< instruct << endl;
initVariable();
}
}