Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-02-17 07:16:43


scott wrote:
>
> Hoping you guys dont mind, but i have summarized some recent
> messages WRT the original question.
>
> Which was "is there room for 2?"
>
> DG mentioned boost::threads. And you guys kinda sorted out how
> to make an object equivalent to a thread (using boost::threads)?

Not really, no. An object can never be equivalent to a thread. These are two
separate concepts.

You can kinda tie the lifetime of a thread with the lifetime of the object
and make the one accessible from the other, but that doesn't make them
equivalent; they are still separate entities held together by duct tape. And
once you reach a certain complexity threshold the "a thread is an object"
pattern will limit your options.

It is better to keep the object and the thread separate (I'll use Andreas
Huber's suggestion for the example):

    shared_ptr<ActiveObject> px(new ActiveObject(...));
    thread exec( bind(&ActiveObject::run, px) );

Now you have access to the object via px, and you have access to the thread
via exec. You can throw away both px and exec and the thread will still
continue to execute normally since it keeps a reference to *px and won't let
it die.

Furthermore, this separation allows you to execute an ActiveObject
synchronously without a thread, if you like:

    px->run();

and it also allows you to execute an ActiveObject in a thread pool:

    my_thread_pool pool(16, 4);
    pool.queue( bind(&ActiveObject::run, px) );

Note that in these two examples, there is no one-to-one correspondence
between the active objects and the threads.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk