调用 std::packaged_task::get_future() 时可能出现的竞争条件

Joh*_*ohn -1 c++ future race-condition c++11

在这个文档中看到,有一个演示片段:

std::packaged_task<int()> task([]{ return 7; }); // wrap the function
std::future<int> f1 = task.get_future();  // get a future
std::thread t(std::move(task)); // launch on a thread
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我像这样重写代码片段,是否存在任何潜在的问题(竞争条件):

std::packaged_task<int()> task([]{ return 7; }); // wrap the function
std::thread t(std::move(task)); // firstly launch on a thread, and then gets a future
std::future<int> f1 = task.get_future();  // get a future
Run Code Online (Sandbox Code Playgroud)

更新1 :我理解 Nicol Bolas 的答案,如果我像这样重写代码片段,是否存在任何潜在的问题(竞争条件):

std::packaged_task<int()> task([]{ return 7;});
thread_callablefunc_queue.push_back(task);  //task may be popped and run by another thread at once, queue is protected by mutex.
std::future<int> f1 = task.get_future();  // get a future
Run Code Online (Sandbox Code Playgroud)

让我担心的是,当前线程正在调用时,可能会立即task另一个线程调用。task.get_future()

Nic*_*las 5

是的,有问题。你移动了task. 你的线程不再有它了;task此时的变量处于有效但未指定的状态。你不能要求它的未来,因为它不代表有问题的任务......因为你移动了它。

这不是竞争条件;而是竞争条件。它在功能上与此没有什么不同:

std::packaged_task<int()> task([]{ return 7; });
auto t(std::move(task));
std::future<int> f1 = task.get_future();
Run Code Online (Sandbox Code Playgroud)

task已被移走,因为这就是您要求做的。