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
|
#define _THREADS 4
#include <fstream>
#include <iostream>
#include <thread>
#include <string>
#include <cassert>
#include <cerrno>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <Windows.h>
#include <sys/stat.h>
#include "Node.h"
#include "Hashtable.h"
using std::vector;
using std::string;
using std::thread;
using std::cout;
using std::ifstream;
using std::cin;
typedef unsigned int uint;
void read(const string& ifname, HashTable<Node*>& table, uint startByte, uint endByte);
off_t getFileSize(const string& ifname);
int main(int argc, char** argv) {
HashTable<Node*> myTable;
string ifname;
off_t fileSize = 0;
vector<thread> manager;
cout << "Enter the filename: ";
cin >> ifname;
fileSize = getFileSize(ifname);
for(uint i = 0; i < fileSize; i + (fileSize % _THREADS)) {
manager.push_back( thread(read, ifname, myTable, i, i + (fileSize % _THREADS)) );
} // END for(i)
for(uint i = 0; i < _THREADS; i++) {
manager[i].join();
} // END for(i)
system("Pause");
return 0;
} // END main(argc, argv)
void read(const string& ifname, HashTable<Node*>& table, uint startByte, uint endByte) {
ifstream fin(ifname);
assert(fin);
fin.ignore(startByte / sizeof(char), EOF);
uint byteCount = 0;
string temp;
Node* newNode = nullptr;
while (!fin.eof() && (fin >> temp) && (byteCount <= endByte) ) {
Node* cur = table.retrieve(temp);
if (cur) {
cur->upCount();
} else {
newNode = new Node(temp);
table.insert(temp, newNode);
newNode = nullptr;
} // END if/else
byteCount += sizeof(char) * temp.length();
} // END while( (fin >> temp) && !fin.eof() )
fin.close();
return;
} // END read(ifname)
off_t getFileSize(const string& ifname) {
struct stat st;
if(stat(ifname.c_str(), &st) == -1) {
throw std::runtime_error(std::strerror(errno));
} // END if
return st.st_size;
} // END getFileSize(ifname)
|