[Israel.pm] critical section

Shlomi Fish shlomif at iglu.org.il
Wed Oct 20 13:08:16 PDT 2010

Hi Chanan,

may I request that when replying to my E-mails, you avoid top-posting. See:


On Wednesday 20 October 2010 10:30:16 Chanan Berler wrote:
> Hi Shlomi,
> Thanks for you quick answer. here are some insights regarding my code:
> 1) When openning a new file handler and leaving the sub, will it not
> close the file and release the resource - although it
>     depends on the grabage collector...

If the file-handle is accessible from a different part of the code, it will 
remain open. Else, it will be closed, and the lock you had on the associated 
file will be lost, and a different process can open it. So the lesson (מוסר 
השכל) is: keep the filehandle open and make sure it does not go out of scope 
as long as you want to hold the lock. 

> 2) Also when trying the enter critical section L1, and then trying to
> enter critical section L2, and then close critical
>     section L2, how will perl know how to close critical section L1 -
> since the file handler is the same ?

You cannot lock one file with two different locks or at least you shouldn't 
try. Open two file-handles to different paths on the file-system for that. 

> 3) How will this work when our game server is process (fork), same
> resources are shared.

flock() works across processes (at least on the same box - maybe with NFS it 
will also work across hosts).

> 4) will using LOCK_UN flag and flock - will it remove the file for me,
> after closing the file ? or do i need to use unlink

Don't remove the file. Keep it there, and make sure it can be re-used for 
further locking. Why do you think you need to remove it?

> 5) Is there a better way to lock critical sections, CPAN modules...I
> have notices the flock is not recommanded when trying
>    to lock over the network (our game servers are running apache and
> sending requested using http/https)
>    PS: I though ot using mySQL with cache database, for locking - but
> was told the IO overhead will be worse
>          (this is way they used filesystem locking files).

If you want networked locking you can write a locking service using POE ( 
http://poe.perl.org/ ) or whatever which will use a custom protocol (based on 
TCP, HTTP, etc.) to lock and unlock. Just beware of stale locks in this case.

Note that it's possible flock() will work across hosts if you mount the file-
system using NFS.

> thanks
> Chanan

You're welcome.

> Thanks
> Chanan

Shlomi Fish       http://www.shlomifish.org/
"The Human Hacking Field Guide" - http://shlom.in/hhfg

<rindolf> She's a hot chick. But she smokes.
<go|dfish> She can smoke as long as she's smokin'.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

More information about the Perl mailing list