I would like to create a class whose methods can be called from multiple threads. but instead of executing the method in the thread from which it was called, it should perform t
You should take a look at the Boost ASIO library. It is designed to dispatch events asynchronously. It can be paired with the Boost Thread library to build the system that you described.
You would need to instantiate a single boost::asio::io_service
object and schedule a series of asynchronous events (boost::asio::io_service::post
or boost::asio::io_service::dispatch
). Next, you call the run
member function from n threads. The io_service
object is thread-safe and guarantees that your asynchronous handlers will only be dispatched in a thread from which you called io_service::run
.
The boost::asio::strand
object is also useful for simple thread synchronization.
For what it is worth, I think that the ASIO library is a very elegant solution to this problem.
There's Futures library making its way into Boost and the C++ standard library. There's also something of the same sort in ACE, but I would hate to recommend it to anyone (as @lothar already pointed out, it's Active Object.)