繁体   English   中英

如何在不使用std :: async的情况下使用std :: future?

[英]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_forwait_until不工作“造成的_Running领域的future设置为false,并作为这样的状态, future总是推迟。 如何在不使用std::async情况下使用std::future

找到通过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引用-修正-在视觉工作室-2013 /

Promise提供的未来无用的等待功能

使用承诺提供的未来存在很大的弊端。 由于Visual Studio 2012中的错误,此类future对象的wait_forwait_until方法返回future_status::deferred而不是future_status::timeoutfuture_status::ready ,使这些方法无用。

暂无
暂无

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

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