2016-05-02 70 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