简体   繁体   English

C ++ / Boost:如何发出异步任务完成信号?

[英]C++ / boost : how to signal async task completion?

I have a thread pool which executes tasks asynchronously. 我有一个异步执行任务的线程池。 But I need to wait for a certain task to complete before proceeding (running the task in current thread is not allowed, the task must be run by a worker thread). 但是我需要等待某个任务完成后再继续(不允许在当前线程中运行该任务,该任务必须由工作线程运行)。

What's the easiest way to achieve this using C++11 or Boost? 使用C ++ 11或Boost实现此目的的最简单方法是什么?

  pool.enqueue([]() {
    std::this_thread::sleep_for(2s); // task 1
    // notify task 1 completion???
    std::this_thread::sleep_for(2s); // task 2
  });
  // wait until task 1 is complete???

If you have a thread pool, either the pool should handle the dependencies or you should chain the continuation task from the first task directly. 如果您有线程池,则该池应该处理依赖项,或者应该直接从第一个任务链接继续任务。

Otherwise, the pool can deadlock. 否则,池可能会死锁。 Imagine just for example a pool with 1 thread. 想象一下,例如具有1个线程的池。 It would block indefinitely. 它将无限期地阻塞。 Same can occur with many threads given enough task inter dependencies. 给定足够的任务相互依赖关系,许多线程也会发生同样的情况。

Use std::condition_variable: 使用std :: condition_variable:

std::mutex m;
bool task1_done=false;
std::condition_variable cond_var;
  pool.enqueue([&cond_var, &task1_done]() {
    std::this_thread::sleep_for(2s); // task 1
    // notify task 1 completion
    task1_done=true;
    cond_var.notify_one();
    std::this_thread::sleep_for(2s); // task 2
  });

  // wait until task 1 is complete
  std::unique_lock<std::mutex> lock(m);
  while( !task1_done ) {
    cond_var.wait(lock);
  }

You can use mutex and wait_for/wait_until 您可以使用互斥锁和wait_for / wait_until

You can look example 你可以看例子

Going to answer my own question. 要回答我自己的问题。

I ended up using a future: 我最终使用了未来:

  std::packaged_task<int()> task1([]() {
    std::this_thread::sleep_for(2s); // task 1
    return 1;
  });
  std::future<int> task1result = task1.get_future();
  std::thread thread1([&]() {
    task1();
    std::this_thread::sleep_for(2s); // task 2
  });
  int rc1 = task1result.get();
  printf("task1 complete: %d\n", rc1);
  thread1.join();
  printf("thread complete\n");

And no, there is no chance for a deadlock since there is no cyclic dependency between the threads (the waiting thread is not part of the pool). 不,因为线程之间没有循环依赖性(等待线程不是池的一部分),所以没有死锁的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM