K
K
kozura2014-09-01 16:24:45
C++ / C#
kozura, 2014-09-01 16:24:45

How to use boost to process post messages in a worker thread?

It is necessary to process messages in the order they are called.
Roughly speaking, an analogue of WaitForMultipleObjects on Win32, only with the help of boost.
For example:

/////////// UPDATE ///////////

void thread()
{
  while (true) {
    switch (event) {
    case do_event1:
      // something code...
    break;
    case do_event2:
      // something code...
    break;
    case close_event:
      // terminate thread...
    return;
    }
  }
}

//...

void FooClass1::addMessage()
{
  // something code...
  post_event(do_event1);
}

//...

void FooClass2::addMessage()
{
  // something code...
  post_event(do_event2);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lolshto, 2014-09-01
@Lol4t0

If the task is to perform some actions in a worker thread (or a pool of worker threads), then you can use the boost.asio library, in particular, in order to execute some code in a separate thread pool, you can use io_service::dispatch or io_service::post In general, you can look at the capabilities of boost.asio, perhaps something else may come in handy.
As far as I know, there is no ready-made event library in boost. On the other hand, it is not too difficult to implement it yourself using a queue and a conditional variable. Such a solution is supposed to be more lightweight, but requires more care in implementation, and indeed a bicycle.

V
vScherba, 2014-09-11
@vScherba

In general, your example is just the most correct, modern and scalable approach to the interaction of threads through messaging. It is called MPI (Message Passing Interface) . In Erlang and D, for example, it is used as the default mechanism for thread communication.
Boost just has a plus wrapper over MPI . I have not had to use it, the docks immediately tell how cool everything works between processes. I suspect that the in-process mechanism is also present there as a special case.
As @Lol4t0 said, you can use boost::asio::io_service, although this approach is aimed more at I / O completion events (there is a pure implementation of the Proactor pattern), but no one forbids using pure dispatch or post and getting such a semblance of MPI.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question