C++ Non-Blocking ASIO Run

流过昼夜 提交于 2019-12-10 20:13:51

问题


I have created a series of functions that talk to Libcurl Multi and download files asynchronously via ASIO and Boost.

Obviously though when I call io_service.run it blocks my main thread when it is run. I have tried to make it non blocking but my app crashes.

I was wondering what is the simplest and best approach to running this in the background, in a non-blocking manner and have it call a call-back function when it is done (Like how you can do it in javascript).

So I could just go:

Runthisinthebackground( thingtodo, callback); 

It would run the thingtodo and return the result to the callback. One thing though this must use Libraries such as boost that can run on devices with out C++ 11 as its for a mobile app running on Android and iOS


回答1:


Run io_service in another thread and post to it your functions:

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


来源:https://stackoverflow.com/questions/17321506/c-non-blocking-asio-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!