我如何使用std::future而不使用std::async
How can I use std::future without using std::async?
我使用两个boost::interprocess::message_queue
进行进程间通信。一个用于发送命令,另一个用于接收回答。当我发送命令时,我创建了一个std::promise
,它将std::future
对象返回给函数的调用者
std::shared_future<bool> PluginMQAdapter::exec(const std::string& exec_str) const
{
std::lock_guard<std::mutex> lk(mtx);
promise_queue.push(std::make_shared<std::promise<bool> >());
need_exec_queue.push(exec_str);
return promise_queue.back()->get_future();
}
接收到结果后
int number = 0;
if(recv_mq->try_receive(&number, sizeof(number), recvd_size, priority) && !promise_queue.empty())
{
promise_queue.front()->set_value(number != 0);
promise_queue.pop();
}
在这种情况下如何轮询std::future
?wait_for
和wait_until
不工作,因为future
的_Running字段被设置为false,因此future
的状态总是被延迟。如何使用std::future
而不使用std::async
?
找到boost::shared_future
的解决方案
auto result = exec(exec_str);
const unsigned int wait_msec = 10, max_wait_msec = 5000;
unsigned int i = 0;
while(!result.is_ready() && i < max_wait_msec)
{
std::this_thread::sleep_for(std::chrono::milliseconds(wait_msec));
i += wait_msec;
}
if(result.is_ready())
return result.get();
使它成为标准的问题是什么?
短版本也可以
boost::future_status ok = result.wait_for(boost::chrono::milliseconds(max_wait_msec));
if((ok == boost::future_status::ready))
return result.get();
如果您使用的是Visual Studio 2012(问题中没有提到),那么这就是实现中的错误,在Visual Studio 2013中修复。引用自http://cpprocks.com/44-c11-bugs-fixed-in-visual-studio-2013/
promise
提供的无用的等待函数使用由承诺提供的未来有一个明显的缺点。由于Visual Studio 2012中的一个bug,这些
future
对象的wait_for
和wait_until
方法返回的是future_status::deferred
而不是future_status::timeout
或future_status::ready
,使得这些方法无效。
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 可能的 std::async 实现错误 Windows
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?
- 使用 g++8 和 c++20 的 std::async 编译问题
- 如何有效地使用 std::async 对指针数组执行操作
- 如何从 std::async 任务返回 std::tuple
- 使用 std::bind 将 QTimer::singleShot 传递给 std::async
- 如何将函数及其参数传递给成员函数内的 std::async
- 从 VS2013 到 VS2017 std::async 不会启动新线程
- 使用 std::async 调用模板函数的正确方法是什么?
- C++ - 使用 std::async 时显示进度条
- Clang 崩溃,在 std::async 中出现字符 * 异常