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

元气小坏坏 提交于 2019-11-29 18:09:42
Igor R.

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

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