Good day. I need your help: I ​​have two functions - I alternate them (multithreading) I need the first function after I finish work (I have the text and I write it in the queue and when I can’t leave the words to report) I’ve informed the second function that I’ve already finished work, and the second function got it through multithreading. thank

Code:

std::mutex mutex; std::queue<std::string> queue; std::condition_variable conditionVariable; void ProduceData() { const char* pathToFile = "D:\\text.txt"; std::ifstream stream(pathToFile); if (!stream) { std::cout << "Can not open file\n"; return; } const std::uint8_t maxWordCount = 5; std::string word; while (stream >> word) { std::lock_guard<std::mutex> lockGuard(mutex); for (std::uint8_t count = 0; (count < maxWordCount) || (count != '\0'); ++count) queue.push(word); conditionVariable.notify_one(); } } void ConsumeData() { while (true) { std::unique_lock<std::mutex> uniqueLock(mutex); conditionVariable.wait(uniqueLock, [] {return !queue.empty(); }); while (!queue.empty()) { const std::string& str = queue.front(); std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel); std::cout << str << "-" << numVowels; queue.pop(); } uniqueLock.unlock(); } } 
  • What have you got? Add the code directly to the question. - 0xdb
  • mutex / conditional variable, producer-consumer - KoVadim
  • Use conditional_variable - MrBin
  • @MrBin and you can give an example of using conditional_variable. Or a link where I can see an example of use - dima slon
  • Here is MrBin

0