我想从字符串线程明智地读单词。意思是一个线程读取一个单词,当所有单词完成时,所有线程都应该退出并行。在这个例子中,字符串中有11个字,并且有4个线程在该字符串上运行。但是该程序在运行时会被挂起。我无法找出问题。我也尝试过递归,但这并没有奏效,并被绞死。不能强制在C++中顺序执行线程?僵局?
#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;
}
这是你的完整问题吗? –
该程序正在被绞死。我无法强制顺序执行。 – user3798283