SPUG: Perl Question?

Marc M. Adkins Perl at Doorways.org
Thu May 12 11:19:07 PDT 2005

DeRykus, Charles E wrote:
>>For this whole thread I have to admit that I've been thinking people are wasting 
>>their time trying to figure ways around using a real mutex facility that's supported 
>>by the operating system.  Surely the answer is that you should use the CPAN module 
>>that encapsulates this in some reasonably elegant way, right?
>>Problem is that I can't find it.  Is there such a beast?  Seems like an obvious need.  
>>Candidates like Win32::Mutex fail for obvious reasons. IPC::Semaphore seems like it'd 
>>be the right tool for the job, but despite the name it doesn't appear to be portable 
>>("SysV Semaphore IPC object class" pretty much takes it out of contention).  
>>What am I missing?
> I wonder if  flock with an external file would be reasonably portable..  
> (seems to work on Win32 and Solaris).  
> use Fcntl qw(:flock);
> BEGIN { open MYLOCK, '>', 'mylock' and flock MYLOCK, LOCK_EX|LOCK_NB 
>          or die "already running\n";
>       }

I've been using this mechanism on Windows for almost two years now.  I 
can attest to its utility there but I'm not writing cross-platform code 
just now so YMMV on other operating systems.

I use Win32::Mutex when the lock is only to be used on a single machine. 
  The flock() mechanism works across the network, however, so it can be 
used for processes that are distributed.  I actually write a line to the 
file when the lock is acquired and again when it is released.  On rare 
occasions it is useful to be able to track down the lock's usage, though 
I do end up having to manage the size of the lock file ('lock log' as it 
were) to prevent it from eating the disk.

I have not seen a portable mutex either.  I would guess that no one has 
seen reason to write up the solution with flock() since (a) it's really 
simple and (b) flock() is part of the core.  But maybe someone has and I 
just missed it.


More information about the spug-list mailing list