How to use 2 or more threads for count a words in a file

59 Views Asked by At

I wanna make a program which count a words from file in multiple threads, but my program can count it only in one thread, i want to count this more than one thread (and theoretically make my program work faster (file would have much words)) When i input a 1 chunkSize all good, but if i input a 2 or more i have a error

#include<iostream>
#include<fstream>
#include <mutex>
#include <thread>
#include <sstream>
#include <vector>
std::mutex text_mutex;

int countWords(const std::string& str) {
std::stringstream ss(str);
std::string word;
int count = 0;

while (ss >> word) {
    count++;
}

return count;
}

int countWordsInChunks(const std::vector<std::string> &chunks) {
int totalWords = 0;

for (size_t i = 0; i < chunks.size(); i++) {
    totalWords += countWords(chunks[i]);
}

return totalWords;
}

int main()
{
char pat[100];
unsigned long long res{ 0 };
std::cin >> pat;


std::ifstream fin(pat);
if (!fin.is_open()) {
    std::cerr << "Error opening file." << std::endl;
    return 1;
}

std::vector<std::string> textSplit;
for(std::string line;std::getline(fin,line);textSplit.push_back(line));

std::cout << "Enter a chunk size ";
size_t chunkSize{};
std::cin >> chunkSize;

size_t totalLength{ textSplit.size() };
std::vector<std::vector<std::string>> chunks;


std::thread t1([&]() {
    text_mutex.lock();
    for (size_t i = 0; i < totalLength; i += chunkSize) {
        std::vector<std::string>::const_iterator start = textSplit.begin() + i;
        std::vector<std::string>::const_iterator end = textSplit.begin() + std::min(i + chunkSize, totalLength);

        std::vector<std::string> chunk(start, end);
        chunks.push_back(chunk);
    }
    text_mutex.unlock();
});

std::thread t2([&]() {
    text_mutex.lock();
    for (size_t i = 0; i < chunkSize; i++)  
    {
        res += countWordsInChunks(chunks[i]);
    }
    text_mutex.unlock();
});

t1.join();
t2.join();
std::cout << "\n" << res;
return 0;
}
0

There are 0 best solutions below