2016-05-02 71 views
2

我想从字符串线程明智地读单词。意思是一个线程读取一个单词,当所有单词完成时,所有线程都应该退出并行。在这个例子中,字符串中有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; 
} 
+0

这是你的完整问题吗? –

+0

该程序正在被绞死。我无法强制顺序执行。 – user3798283

回答

4

您从未通知过条件变量。它从未醒来。所有线程都在等待发生的事情。通知你print函数的末尾:

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. 
} 

您还需要全局变量初始化i为零,或者你将有不确定的行为。

+0

他不需要在主要的初始通知吗? – kfsone

+0

否。根据[cppreference.com](http://en.cppreference.com/w/cpp/thread/condition_variable/wait),用谓词对'wait'的调用等价于while(!pred( ))wait(lock);' - _i.e._谓词首先被测试。因此,所有线程都将等待除线程0之外的条件,这将立即执行并通知。 – paddy