On Fri 07 Nov 2008, Steven Siebert wrote:
> Is there any way to have a MPM-safe (specifically thread-safe)
> singleton pattern?

Modperl manages an interpreter pool if it runs under a threaded MPM.
That means the first modperl-related action in the request cycle pulls
an interpreter from the pool. Some time later the interpreter is the
put back to the pool. The point in time when that happens is defined by
the PerlInterpScope directive. It can happen immediately after the
current phase in the request cycle or when the request is over or when
the client connection is dropped. (And you can have a separate
interpreter for a subrequest.) Perl variables allocated in one
interpreter are accessible only from that interpreter unless they are
marked as shared. Shared variables are implemented by the
thread::shared module. This module creates another "shared" perl
interpreter that does the actual memory management. A shared variable
is then allocated inside that special interpreter and another one is
allocated inside the current interpreter. Then that variable is "tied"
to the variable in the shared interpreter in a similar way to what the
tie() command does.

So for what you want you need to make sure (if I understood your
problem) that the same instance is used throughout the request cycle.
Plus you want that it is destroyed when the request is over.

The simplest way is to put the object as a pnote:

sub getInstance {
my $r=shift;

return $r->pnotes->{Logger} if exists $r->pnotes->{Logger};
return $r->pnotes->{Logger}=Logger->new;

No global $this!

When the request pool is destroyed all pnotes are destroyed as well.

In theory that also binds the current interpreter to the pool. That
means it makes sure that the interpreter stays the same at least as
long as the request pool exists no matter what PerlInterpScope says.
But there were bugs with that in the past. So perhaps you have to
upgrade your modperl.

And finally an advice, don't use a threaded MPM with modperl in
production! If you want to help with the code it would be appreciated.
A good starting point is the threading branch at


Need professional mod_perl support?
Just hire me: torsten.foertsch@gmx.net