Boost logo

Boost :

From: Kaz Kylheku (kaz_at_[hidden])
Date: 2000-09-11 18:11:56

On Mon, 11 Sep 2000, Larry Evans wrote:

> I've attached a file which I hope illustrates why I still don't agree.

Your program has a serious flaw; the object ``sp1'' is being inappropriately
shared by two threads.

You create a thread and give it the pointer to the local auto object ``sp1''.
As that thread races ahead, your main thread proceeds to *reuse* that sp1
object for another purpose: to point to another new reference counted object.

It's impossible to tell which object the newly created thread gets, pointee1 or
pointee2, never mind the correctness of the reference counting!!!

Part of the problem is that you are trying to hand off the ownership of the
reference counted object by passing the smart pointer. This is a case in which
avoiding smart pointers would be simpler: as the pthread_create paramter, pass
pointee1 directly and then never refer to it again in the main thread. You
could pass the smart pointer itself as you currently do, but again, you must
not touch that smart pointer object again---it is in use by the other thread!

Keep in mind that it can be dangerous to even pass pointers to automatic
storage to other threads; you have only gotten away with it because you do a
pthread_join() in the same statement block.

On another note, as a matter of style, I would write the RefCountAny class
differently: the constructor should set the initial refcount to 1, not zero.
That indicates that the object is constructed and ready for use. An object with
a refcount of zero is dead, or just about! If you make that change, the smart
pointer class's constructor then must not increment the reference, of course,
just store the pointer. Consider that if you construct the object with
reference count 0, then you cannot do this:

        RefCountAny *obj = new RefCountAny;
        obj->decr_nref(); // error, refcount goes to -1!

Hope this helps.

Boost list run by bdawes at, gregod at, cpdaniel at, john at