2016-05-02 1 views
2

私は文字列のスレッドから賢明な単語を読み込もうとしています。 1つのスレッドが1つの単語を読み込むことを意味し、すべての単語が終了すると、すべてのスレッドも平和的に終了する必要があります。この例では、文字列に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

関連する問題