Joost has asked for the wisdom of the Perl Monks concerning the following question:
Currently I'm working on a XS/C++ system on linux w/ pthreads. Many of the objects in the system are intended to be shared across perl threads (for various reasons - but mainly memory efficiency).
My question now is: assuming an object is shared, is there any way to know in how many perl threads it's referenced?
This is important to know, because apparently if a shared object goes out of scope in one thread, the default behavior is to call DESTROY() on it, which calls delete(), which makes the object unusable for any other threads that are still running.
Currently I'm doing something like this (ThreadCounted is a base class for objects that are shared but need to be destroyed when they're out of scope in all threads):
In other words, I'm assuming the objects are shared across all threads, and the object is only deleted when the last thread has called DESTROY on it.pthread_mutex_t ThreadCounted::mutex = PTHREAD_MUTEX_INITIALIZER; unsigned int ThreadCounted::threadcount = 1; ThreadCounted::ThreadCounted() { pthread_mutex_lock(&mutex); threadrefs = ThreadCounted::threadcount; pthread_mutex_unlock(&mutex); } ThreadCounted::~ThreadCounted() { } void ThreadCounted::CLONE() { pthread_mutex_lock(&mutex); ThreadCounted::threadcount++; pthread_mutex_unlock(&mutex); } void ThreadCounted::DESTROY() { pthread_mutex_lock(&mutex); if (--threadrefs == 0) { delete this; } pthread_mutex_unlock(&mutex); }
Also, I'm assuming the class is loaded when there's only one thread running, and the thread count is incremented every time CLONE() is called.
This has some disadvantages, mainly that (AFAIK) I can't tell when a thread is stopped (i.e. there's no hook corresponding to the "inverse" of CLONE). Also it's possible for an object to be shared only by a subset of the threads (again, AFAIK) and I won't be able to tell.
I'd appreciate any insights & comments.
Cheers,
Joost.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: threads, refcounting, XS, DESTROY
by Anonymous Monk on Aug 15, 2007 at 16:08 UTC | |
by Joost (Canon) on Aug 15, 2007 at 18:28 UTC | |
by Anonymous Monk on Aug 28, 2007 at 15:00 UTC |