Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-08-18 11:52:45


From: "Alexander Terekhov" <terekhov_at_[hidden]>
> > A noncopyable thread object _is_ a perfect fit
> > for the thread concept if you can guarantee that
> > there is one to one correspondence between the actual
> > threads and the C++ thread objects.
>
> agree.
>
> > Such a design is possible:
> >
> > thread & create(F f);
> > thread & current();
> >
> > [where current() called from within 'f' would
> > return a reference to the same thread object as
> > create().]
>
> i think that the following is also possible:
>
> thread mythread( f );
>
> [where current() called from within 'f' would
> return a reference to mythread thread object]

It is, but it has its problems. The important question is, who controls the
thread object lifetime; is it the library, or the user.

When the library manages the lifetime of the thread object, we have the
design I outlined, where create() and current() return a thread &, or
shared_ptr<thread>, or thread::ref. The thread object lives until the thread
terminates (in the thread& case) or until the thread terminates and there
are no more references to the object.

When the user explicitly creates thread objects, as in the current design
and your example, current() can't return a reference since the thread object
may have already been destroyed (but the actual thread still runs.) The best
you can do is

thread * current();

where current() returns 0 when the thread object has been destroyed.

I personally prefer the library-managed lifetime approach, but I'm obviously
in the minority.

> > Unfortunately, without garbage collection, the references would become
> > invalid when 'f' returns (without warning.)
>
> why? for "joinable" threads when f returns, nothing terrible
> (with respect to thread objects - C++ and/or native) really
> happens.. only "join" would explicitly destroy native thread
> object (after awaiting thread termination, implicit destruction
> via "detach" aside; IMHO that should only be done for dynamic
> C++ thread objects; btw native thread objects (represented by
> pthread_t/HANDLE) are always dynamic).

Because the thread may run to completion without being joined, and the
thread object will have to be destroyed, invalidating references.

--
Peter Dimov
Multi Media Ltd.

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