Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top