我如何使用std::future而不使用std::async

How can I use std::future without using std::async?

本文关键字:std async future 何使用      更新时间:2023-10-16

我使用两个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_forwait_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_forwait_until方法返回的是future_status::deferred而不是future_status::timeoutfuture_status::ready,使得这些方法无效。