2

First time using threads in C++. I've been looking at using boost which is very confusing for me. Basically all I'm trying to do is:

  1. Create a worker thread that does some work asynchronously. Continue main thread while work is being done.
  2. When the worker thread is done, fire a callback function with some results that executes in the main thread context.

So something similar to thread handling in C#.

There doesn't seem to be any support for 2. Using an io_service together with an async function, and thereafter using run() on the io_service seems to block the main thread. So not very asynchronous.

I've tried using boost::future as per the example here: Using boost::future with "then" continuations

Here the "then" continuation is done in a separate thread, not the main thread, so not what I'm after. Is there any way to alter this? Using boost::launch::deferred and wait() makes the call synchronous, so that doesn't help either. Same with just using get() on the boost::future construct.

It seems the only option is to create a mutex-locked shared event queue, and just poll it continuously for new data in the main thread?

Community
  • 1
  • 1

1 Answers1

1

It's unusual to preempt the main thread in whatever it was doing to start working on the callback. Even in "thread handling in C#" (which is quite a broad subject) the main thread will typically process callbacks when it is processing the thread's message queue.

So typically, the main thread only executes callbacks when it is ready to do so. One way of implementing that is by calling run() on an io_service.

Your main thread can only process one message queue at a time. If your application happens to be a Windows GUI application, then your main thread is already processing a message queue (the windows message queue) and should not perform a blocking function call like run() on an IO service (which is handling another message queue). In such a case, you can decide to write code that wraps your callback in a windows event message and process that.

If you happen to be using Qt, then the answer to this question shows you how you could combine an asio io_service with your message loop (I haven't tried that one).

If your process is not a GUI application, then, since you already seem to be somewhat familiar with asio, you could still use an io_service. In that case however, all functions that the main thread performs (after initialization) should be run as events on that message queue. For example: "Continue main thread" in your question could then be implemented as another callback on the io_service.

Community
  • 1
  • 1
dhavenith
  • 2,028
  • 13
  • 14