2016-07-12 5 views
-2

マルチスレッドは初めてです。ここに私が欲しいものがありますC++ multithreading:条件変数

thread_function(){ 
    // do job1; 
    //wait main thread to notify; 
    // do job2; 
} 
main(){ 
    //create two threads 
    //wait both threads to finish job1 
    //finish job3, then let both threads start job2 
    //wait both threads to join 

} 

どうすればいいですか?ありがとう。ここで

は私のコードは、私の質問は、私は一つの機能にJOB1とJOB2を組み合わせ、および順序を制御するために、条件変数を使用できるかどうかである

void job1(){ 
} 
void job2(){ 
} 
void job3(){ 
} 
int main(){ 
    thread t11(job1); 
    thread t12(job1); 
    t11.join(); 
    t12.join(); 
    job3(); 
    thread t21(job2); 
    thread t22(job2); 
    t21.join(); 
    t22.join(); 
} 

のですか? 「Q」の下

+0

最も良い方法は、一束を研究してから、いくつかのコードを書くことです。あなたの個人的なコード作成サービスではありません。 –

+0

あなたが試したことを教えてください。 – Brian

答えて

0

私はこれは、あなたが探している正確な解ではありませんが、コードがご案内しますの下にあなたのサンプル(生産者 - 消費者問題に似たもの) を与えるだろう、

は、ミューテックスで保護されています条件変数が通知を受け取るのを待つか、または!q.empty(偽の起床に必要)またはタイムアウトが発生します。

std::condition_variable cond; 
std::deque<int> q; 
std::mutex mu; 

void function_1() { 
    int count = 50; 
    while (count > 0) 
    { 
     // Condition variables when used lock should be unique_lock 
     // lock the resource 
     std::unique_lock<mutex> locker(mu); 
     // defer the lock until further 
     //std::unique_lock<mutex> locker(mu, std::defer_lock); 

     q.push_front(count); 
     locker.unlock(); 
     //cond.notify_one(); 
     cond.notify_all(); 
     //std::this_thread::sleep_for(chrono::seconds(1)); 
     count--; 
    } 
} 

void function_2(int x,int y) { 
    int data = 0; 
    while (data != 1) 
    { 
     // mu is the common mutex this resource is protected for the q. 
     std::unique_lock<mutex> locker(mu); 
     // this will only be done when !q.empty() 
     // This will make sure it is handled by multiple threads 
     auto now = std::chrono::system_clock::now(); 
     if (cond.wait_until(locker, now + y * 100ms, []() { return !q.empty(); })) 
     { 
      auto nowx = std::chrono::system_clock::now(); 
      cout << "Thread " << x << "waited for " << (nowx-now).count() << endl; 
     } 
     else 
     { 
      cout << "Timed out " << endl; 
      break; 
     } 
     data = q.back(); 
     q.pop_back(); 
     locker.unlock(); 
     cout << x << " got value from t1 " << data << endl; 
    } 
} 

int main() 
{ 
    std::thread t1(function_1); 
    std::thread t2(function_2,1,50); 
    std::thread t3(function_2,2,60); 
    std::thread t4(function_2,3,100); 
    t1.join(); 
    t2.join(); 
    t3.join(); 
    t4.join(); 

    return 0; 
}