This may be considered as OT since the C++ Standard says not one word
about threads. Nevertheless, C++ is routinely and widely used to write
solid multithreaded code.
I wondered if anyone has any pointers/references to invoking callbacks
accross different threads? (google is not showing much promise, and I'm
running out of both time and patience...)
I've used the following pattern successfully with a very complex multithreaded
application:
class Service
{
public:
class Listener
{
public:
virtual void Callback() = 0; // This is the callback function
};
void Do(Listener& listener);
};
The consumer of the service then creates a class that inherits from
Service::Listener to implement the callback, and pass an instance of it to
Do(), which will then call the Callback() method.
And in some cases, the User class can inherit privately from
Service::Listener:
class User: private Service::Listener
{
public:
void Do(Service& service) { service.Do(*this); }
private:
virtual void Callback() { /* ... */ }
};
The nice thing about this pattern is that the particular resource locking and
serialization knowledge is owned by the _user_ of the service, not the service
itself. This lends itself to services that will work in both lightweight (no
synchronization needed) and heavyweight (lots of synchronization needed)
applications with no change.
If you need to synchronize the use of the service, you can either add an
Open()/Close() pair of methods to Service, or add synchronization code inside
Service:
o().
-dr