Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intra-process coordination in mod_perl under the worker MPM

I need to do some simple timezone calculation in mod_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)

How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The docs I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.

Update: yes, I am aware of the need for using Env::C to set TZ.

like image 407
ysth Avatar asked Dec 06 '25 04:12

ysth


1 Answers

(repeating what I said over at PerlMonks...)

BEGIN {
    my $mutex;

    sub that {
        $mutex ||= APR::ThreadMutex->new( $r->pool() );
        $mutex->lock();

        $ENV{TZ}= ...;
        ...

        $mutex->unlock();
    }
}

But, of course, lock() should happen in a c'tor and unlock() should happen in a d'tor except for one-off hacks.

Update: Note that there is a race condition in how $mutex is initialized in the subroutine (two threads could call that() for the first time nearly simultaneously). You'd most likely want to initialize $mutex before (additional) threads are created but I'm unclear on the details on the 'worker' Apache MPM and how you would accomplish that easily. If there is some code that gets run "early", simply calling that() from there would eliminate the race.

Which all suggests a much safer interface to APR::ThreadMutex:

BEGIN {
    my $mutex;

    sub that {
        my $autoLock= APR::ThreadMutex->autoLock( \$mutex );
        ...
        # Mutex automatically released when $autoLock destroyed
    }
}

Note that autoLock() getting a reference to undef would cause it to use a mutex to prevent a race when it initializes $mutex.

like image 185
tye Avatar answered Dec 08 '25 18:12

tye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!