Reputation: 467
I am trying to read words from a string thread wise . Means one thread reads one word and when all the words finished then all the threads should also exit peacefully . In this example there are 11 words in the string and 4 threads are operating on that string . But the program is getting hanged while running . I am not able to identify the issue . I tried recursion as well but that didn't work and got hanged .
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
stringstream s("Japan US Canada UK France Germany China Russia Korea India Nepal");
int count = 0;
string word;
condition_variable cv;
mutex m;
int i = 0;
bool check_func(int i,int k)
{
return i == k;
}
void print(int k)
{
while(count < 11) // As there are 11 words
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
s >> word;
cout<<word<<" ";
i++;
cv.notify_all();
count++;
}
return;
}
int main()
{
thread threads[4];
for(int i = 0; i < 4; i++)
threads[i] = thread(print,i);
for(auto &t : threads)
t.join();
return 0;
}
Upvotes: 2
Views: 267
Reputation: 63471
You never notified the condition variable. It never woke up. All threads are waiting for something to happen. Notify at the end of your print
function:
void print(int k)
{
unique_lock<mutex> lk(m);
int z = k;
cv.wait(lk,[&]{return check_func(i,z);}); // Line 33
cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
i++;
cv.notify_all(); // Wake up all waiting threads - the correct one will continue.
}
You also need to initialize the global variable i
to zero, or you will have undefined behaviour.
Upvotes: 4