问题
I have some code running in a boost thread that modifies stuff handled by the main thread which is not working and it makes sense.
On android i would have the Handler
which is a message queue that would execute my code on the main thread and i can pass whatever parameters i want to this handler.
I want to do the same with boost
so on my main thread i do the following:
boost::thread workerThread(boost::bind(&SomeClass::pollService, this));
My pollService method:
SomeClass::pollService()
{
//get some stuff from a web service
//parse the json response
//NEEDED part: call a function to be executed on the main thread and hand it some functions
}
P.S. I have looked at many io_service.post
examples and i still have no clue how to do it, and also i read an answer that said to use asio
strand
but i am also unable to understand it.
Can some one please dumb it down for me ? Please don't write something so abstract that i won't understand, I am not experienced in this. Thank you
回答1:
Yes, io_service::post()
is a convenient facility to post a functor from one thread to another, but the destination thread should execute io_service::run()
, which is blocking function (it's kind of io_service
"message loop"). So, assuming your main thread looks like this:
int main()
{
// do some preparations, launch other threads...
// ...
io_service io;
io.run();
}
...and assuming you've got an access to io
object from pollService
running in another thread, you can do the following:
SomeClass::pollService()
{
// do something...
// ...
io.post([=] { doStuffThatShoudRunInMainThread(); });
}
If your compiler doesn't support c++11 lambdas, use bind
-- but note that post
expects nullary functor, i.e. a function-object that doesn't accept parameters.
来源:https://stackoverflow.com/questions/13680770/running-a-function-on-the-main-thread-from-a-boost-thread-and-passing-parameters