2017-06-02 21 views
1

私は2つのスレッド、packaged_taskdequeにプッシュし、それを実行する単純なプログラムを持っています。タスクにはthis_thread::sleep_forがあり、「プロセス」スレッドだけがそれを待つことが期待されますが、どちらも待機しており、実行が順次行われます。私は何が欠けているのですか?this_thread :: sleep_for他のスレッドに影響する

#include <future> 
#include <iostream> 
#include <deque> 

std::mutex m; 
std::condition_variable cv; 
std::deque<std::packaged_task<void(int)>> deque; 

void post() { 
    int id = 0; 
    auto lambda = [](int id) { 
     std::this_thread::sleep_for(std::chrono::seconds(std::rand() % 10 + 1)); 
     std::cout << id << std::endl; 
    }; 
    while (true) { 
     std::this_thread::sleep_for(std::chrono::seconds(1)); 

     std::packaged_task<void(int)> task(lambda); 
     task(id++); 

     std::lock_guard<std::mutex> lg(m); 
     deque.emplace_back(std::move(task)); 

     cv.notify_one(); 
    } 
} 

void process() { 
    std::deque<std::packaged_task<void(int)>> to_exec; 
    while (true) { 

     while (!to_exec.empty()){ 
      std::future<void> fut = to_exec.front().get_future(); 
      fut.get(); 

      to_exec.pop_front(); 
     } 

     std::unique_lock<std::mutex> lk(m); 
     cv.wait(lk, []() {return !deque.empty(); }); 

     while (!deque.empty()) { 
      to_exec.push_back(std::move(deque.front())); 
      deque.pop_front(); 
     } 
    } 
} 

int main() { 

    std::thread tpost(post); 
    std::thread tprocess(process); 

    tpost.join(); 
    tprocess.join(); 
} 
+3

'packaged_task'は、それ自体が非同期ではありません。呼び出し可能なのでスレッドコンストラクタに渡すことはできますが、自動的に作成されるバックグラウンドスレッドはありません。おそらく、 'std :: launch :: async' [起動ポリシー](http://)で' [std :: async'](http://en.cppreference.com/w/cpp/thread/async) en.cppreference.com/w/cpp/thread/launch)? –

+0

'task'を作成した直後に' post'で 'task(id ++);'をなぜ呼び出すのですか?ラムダが呼び出されたときにパラメータとして渡されるように、 'id'の値をバインドする意図はありませんか? –

+0

@Someprogrammerdude良い点。私はそれを試みます。 – mathiasfk

答えて

0

私が代わりに寝てランダムな秒をstd::asyncを使用される、より効果的だと思う...

関連する問題