简体   繁体   中英

HOWTO: post messages between threads with Boost::asio?

Sorry for my english

I've searched around, but did not get an answer to this question: I have a windows application project, using boost thread libraries. I want to post messages(or, invoke callbacks) from a worker's thread to the main UI thread. I studied the samples in boost::asio, all of them used in a blocked main thread, but my UI thread is working asynchronous.

Would you please help me? thanks a lot!

Since the UI thread has its own message loop, you can't call in its context the blocking io_service::run() function. What you can do is to interleave a polling UI-related method with io_service::poll_one() :

  // WARINING: untested code
  MSG msg;
  while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    if (io_service_.stopped())
      io_service_.reset();
    error_code ec;
    io_service_.poll_one(ec);
  }

Now, when you post functors to io_service_ , you actually post them to the main GUI thread.

(Certainly, if you use some GUI framework, you should use the appropriate framework method instead of PeekMessage .)

The UI thread is it a webkit similar kind of UI or plain windows forms, because if you are using webkit then u can handle it in a different way. OR Try using Delegates. OR finally if nothing works out, you can run a while loop checking an vector for any new input and add to the vector from the thread callback function.

I prefer if you could use delegate. (pointer function)

Here is a sample code for pointer function:

define a function like this:

typedef boost::function<void(std::string)> fnLog;

or if u want to go specifically for windows then

typedef void (__stdcall *fnLog)(char* val);

fnLog is the function with std::string parameter. then bind your function which is in UI thread to the pointer function

fnLog myPointerFunc = boost::bind( &UI::f1, _1);

then pass

myPointerFunc

as callback.

for more reference check on http://www.radmangames.com/programming/how-to-use-boost-function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM