The author of that code had this to say:

A Thread has a weak reference to itself and a reference (shared_ptr)  
to it's Runnable object

A Runnable has a weak reference to the Thread object.

If a thread creator gives up it's reference to Runnable immediately  
after creating the thread, this guarantees that the Runnable WILL NOT  
be GC'ed.
If a thread creator gives up both its Runnable and Thread before  
invoking Thread.start, this guarantees that both Thread and Runnable  
WILL be GC'ed

In PthreadThread::start the weak ref is converted into a heap-based  
regular ref so that the thread doesn't get GC'ed before  
PthreadThread:threadMain is entered.  In threadMain, the heap-based  
regular ref is replaced by a stack-based ref.
Doing this means that the Thread and Runnable objects WILL NOT get  
GCed until threadMain exits, even if all other references have been  
given up.

So the answer to Vinicius' question is the 2 references are for 1) the  
creator thread and 2) the thread created by  PosixThread::start.  This  
is not a leak and works as designed.  I'm not clear why this would  
show up as a leak in valgrind unless he is not doing a clean exit.


Vinicius Tinti wrote:
> Hello,
> 
> I detect some memory leak in my application using valgrind.
> 
> The leak happen with PosixThread, after call PosixThread.start() the
> reference count of shared_ptr increases by one. When the thread
> loses it scope the count reference is with 2. So, there are 2 smart pointers
> using the thread. One is mine, and the other?
> 
> I found this really strange code in PosixThread.cpp
> 
> PosixThread::start()
> 
> ...
>     // Create reference
>     shared_ptr<PthreadThread>* selfRef = new shared_ptr<PthreadThread>();
>     *selfRef = self_.lock();
> ...
> 
> So, it just creates a local scope smart pointer the let it leak, so, the
> reference count will not be decreased letting my thread leaking.
> 
> Can some one explain me that?
> 
> Sorry by my poor english.
> 
> Thanks.
> 

Reply via email to