异步:boost async & boost future

本文介绍如何使用Boost库进行异步编程,包括boostasync和future的基本用法,以及它们与stdasync的区别。文中还讨论了如何避免阻塞问题,并提供了一些实用的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果需要用到异步(例如 io 等待, 大量计算)执行代码,boost async 和 future 提供了方便的操作:

补充,查看这里:http://blog.youkuaiyun.com/gw569453350game/article/details/50435879

#include <boost/thread/future.hpp>
using namespace boost;
int main()
{
  future<int> f1 = async([]() { return 123; });  // or any heavy computation
  future<string> f2 = f1.then([](future<int> f) { return f.get().to_string(); // here .get() won't block;
}

上面的代码需要保存 f1 变量,否则async返回一个临时的 future 变量,然后就被销毁了,该future的销毁会导致主程序等待异步被执行的函数的返回(即阻塞)。因此,即使不需要使用async 所执行的函数的返回值,也需要用一个f1来保存其返回的future变量,否则会阻塞异步执行(即 async 只有在计算完成后才会返回),例如:

void f()
{
  std::future<void> fut = std::async(std::launch::async, 
                                     [] { /* compute, compute, compute */ });

}                                    // block here until thread spawned by std::async completes

The function blocks until the asychronously running thread completes.

因为:

The thread completion [for the function run asynchronously] synchronizes with [i.e., occurs before] [1] the return from the first function that successfully detects the ready status of the shared state or [2] with the return from the last function that releases the shared state, whichever happens first.

但是如果使用的不是 async,则不会出现阻塞的情况:

void f3()
{
  std::packaged_task<void()> pt(doSomeWork);
  auto fut = pt.get_future();
  std::thread(std::move(pt)).detach();
  ...                          // no get, no wait
}
Now what happens?

Your function returns, even if the function to be run asynchronously is still running.

注意: boost::future 只能 get 一次,第二次get返回的是空!

参考链接
1. http://www.boost.org/doc/libs/1_59_0/doc/html/thread/synchronization.html#thread.synchronization.futures
2. http://scottmeyers.blogspot.hk/2013/03/stdfutures-from-stdasync-arent-special.html
3. http://scottmeyers.blogspot.hk/2013/03/thread-handle-destruction-and.html
4. http://www.boost.org/doc/libs/1_59_0/doc/html/thread/build.html#thread.build.configuration.future

namespace beast = boost::beast; // from &lt;boost/beast.hpp&gt; namespace http = beast::http; // from &lt;boost/beast/http.hpp&gt; namespace net = boost::asio; // from &lt;boost/asio.hpp&gt; using tcp = boost::asio::ip::tcp; // from &lt;boost/asio/ip/tcp.hpp&gt; using TypeCallbackClientOnDone = std::function&lt;void(const char*, const std::string&amp;, const char*)&gt;; // Performs an HTTP GET and prints the response class ClientSession : public std::enable_shared_from_this&lt;ClientSession&gt; { public: // Objects are constructed with a strand to // ensure that handlers do not execute concurrently. explicit ClientSession(net::io_context&amp; ioc, std::shared_ptr&lt;beast::tcp_stream&gt; stream, const std::string&amp; host, int port); // Start the asynchronous operation void Run(int timeout, char const* target, const char* contentType, const std::string&amp; content, const TypeCallbackClientOnDone&amp; cb); // 拿走其内的Stream std::shared_ptr&lt;beast::tcp_stream&gt; TakeStream(); private: void DoRun(int timeout, const std::string&amp; target, const std::string&amp; contentType, const std::string&amp; content, const TypeCallbackClientOnDone&amp; cb); void OnConnect(beast::error_code* ecPtr, int timeout); void OnWrite(beast::error_code ec, std::size_t bytes_transferred, int timeout); void OnRead(beast::error_code ec, std::size_t bytes_transferred, int timeout); void OnFail(const std::string&amp; errMsg, char const* what); void ReportFail(const std::string&amp; errMsg, char const* what); void CloseSocketAndConnect(int timeout); private: net::io_context&amp; ioc_; std::shared_ptr&lt;beast::tcp_stream&gt; stream_; std::string host_; int port_{ 0 }; //用于底层连接复用,是否失败时重连 bool reconnect_{ true }; beast::flat_buffer buffer_; // (Must persist between reads) http::request&lt;http::string_body&gt; request_; http::response&lt;http::string_body&gt; res_; TypeCallbackClientOnDone funcOnDone_; }; 改用strand序列化
最新发布
07-24
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值