Search code examples
c++multithreadingboost-thread

How can I call a function on a different thread using C++?


I'm creating a component that will be consumed by other teams / products. The component allows client code to issue a set of commands, and internally these commands are executed on a worker thread - with a thread safe queue implementation where the commands are added to the queue on the callers (clients) thread, and removed / processed on the worker thread.

I'd like to provide feedback from my component to the client code, in the form 'operation XYZ has completed'. I can easily do this via callbacks, however the callback is called on my worker thread - I'd like it to happen on the callers (clients) thread. How can I do this?

It's a cross platform component (Windows, Linux, OS X). Boost is available. My default development compiler is MS VC++ 2010, i.e. it's not C++11.


Solution

  • The usual way to arrange this type of multithreaded architecture is for each thread to have a blocking queue of functors.

    Each thread loops over its queue, executing each functor in turn.

    To call a function in a different thread you simply create and add a functor to that threads queue.

    To create functors in C++ you can use std::function and std::bind, lamdbas, function objects or function pointers. See std::function

    There is no standard blocking queue, but it is fairly easy to write one with a semaphore and a mutex (which are part of std::thread library afaik, and also part of pthread). Google for "blocking queue"