【问题标题】:C++ Non-Blocking ASIO RunC++ 非阻塞 ASIO 运行
【发布时间】:2013-06-23 16:14:48
【问题描述】:

我创建了一系列与 Libcurl Multi 通信并通过 ASIO 和 Boost 异步下载文件的函数。

显然,当我调用 io_service.run 时,它会在运行时阻塞我的主线程。我试图让它非阻塞,但我的应用程序崩溃了。

我想知道在后台以非阻塞方式运行它并让它在完成时调用回调函数的最简单和最好的方法是什么(就像你可以在 javascript 中那样做)。

所以我可以走了:

Runthisinthebackground( thingtodo, callback); 

它将运行 thingtodo 并将结果返回给回调。但有一件事必须使用诸如 boost 之类的库,它可以在没有 C++ 11 的设备上运行作为在 Android 和 iOS 上运行的移动应用程序

【问题讨论】:

  • FWIW,iOS 和 Android 工具链都支持 C++11。
  • 哦,我不知道 :) 感谢您的提醒 :) 这让事情变得更容易 :)

标签: c++ boost boost-asio libcurl nonblocking


【解决方案1】:

在另一个线程中运行 io_service 并将您的函数发布到它:

asio::io_service io_service;
// give it some work, to prevent premature exit
shared_ptr<asio::io_service::work> work(new asio::io_service::work(io_service));
boost::thread t(&asio::io_service::run, &io_service);
t.detach();
//...
io_service.post(yourFunctor); // yourFunctor will be executed in the separate thread

【讨论】:

  • 干杯 :) 它只是出现内存错误,我想我需要使用该共享指针来共享我的信息
  • 谢谢。使用 boost 1.50 我不得不使用boost::thread t(boost::bind(&amp;boost::asio::io_service::run, &amp;io_service));
  • @Gabriel Devlers 根据to the docs,1.50 已经实现了带有参数的 ctor。
  • 我同意这一点,但 gcc 5.4.0 (with C++0x) 说error: no matching function for call to ‘boost::thread::thread(&lt;unresolved overloaded function type&gt;, boost::asio::io_service*)
  • @Gabriel Devillers 好的,我明白了。那是因为io_service::run 有多个重载,而thread ctor 没有处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多