我想從字符串線程明智地讀單詞。意思是一個線程讀取一個單詞,當所有單詞完成時,所有線程都應該退出並行。在這個例子中,字符串中有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