develooper Front page | perl.perl5.porters | Postings from June 2004

Destructors and iThreads

Thread Next
Eric Garland
June 30, 2004 12:18
Destructors and iThreads
Message ID:
I've been working on a perl module that deals with external resources
(XS interface to a C++ library) and I've been thinking about the best
way to get it to work properly with threads.  I've come up with a few
thoughts which I figured might make a good discussion for Perl 5 Porters.


1.  Destructors are for freeing external resources.

     Perl cleans up all it's own memory so unless you deal with some
     external resource (network connection, C++ object, allocated memory)
     you don't need a destructor.

2.  Any external resource should not get auto-freed when a thread
     exits, only when the whole program exits.

Consider the example of a simple library that uses a thread to
do some work.  This library creates a thread, executes some code
in it, then joins it.  Using this library will cause EVERY SINGLE
EXISTING LIBRARY that has external resources to FAIL (unless it
has been rewriten to detect cloning and not run the destructor).
The end user and programmer may not even know that threading is
going on at all.  A smart library could detect that the version
is higher than 5.8 and decide to use some threads.

This is a bad thing!  It will cause issues like:

If I use Library A it works
If I use library B it works
If I use both it core dumps

as well as issues like:

It works fine on this machine running perl 5.6
It core dumps on this machine running perl 5.8

and fun issues like:

If this thread exit's before I get to this code segment,
it core dumps.  Sometimes it works, sometimes it doesn't.

I don't know how hard it would be to implement something
like Mike Promraning's:

return unless @_ and threads::shared::_refcnt($_[0]) == 1;

as a default wrapper around the destructor but it might be a good
idea to do it since problems like the ones stated above are the
kinds of problems that make people say

"Screw this, I'm using Java"  (shudder)

I think it makes sense to change DESTROY in iThreads to only
execute when all clones have gone away by default and make a
different function, I'll call it DESTROY_INSTANCE that is called
for each object as it goes away just in case someone actually
needs to do something then.  That way, all the XS modules
in existance have a chance at working properly and everyone
who writes an XS module doesn't have to re-implement the same
code for tracking reference counts in their destrcutors or use
a hack like Thread::Bless.

Remember to consider how bad a core dump is for mod_perl.
Issues like these are one of the reasons you can't find an
ISP willing to host mod_perl anymore but PHP is everywhere.


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About