[Rd] File lock mechanisms in R

François Pinard pinard at iro.umontreal.ca
Tue Jul 3 00:58:15 CEST 2007

[Henrik Bengtsson]

>I am looking for a way to have one R session lock a file for
>read/write access, while being updated/modified by another R session.
>This will provide me with a-poor-mans parallelization method.  It is
>ok to have so called advisory looking (as in Unix), which are
>non-mandatory to follow.  If not available, I'll use lock files, but
>there are some potential problems in creating such in an atomic way.
>Ideally I wish to have this working on all platforms.

Something which worked for me, so far, is to create a directory, and see 
if the creation succeeded or failed.  If the creation succeeded, you 
have the lock.  If it failed, something else created it and has the 
lock.  You then keep retrying after some delay.  Of course, the 
directory should not be used outside your locking protocol.

On the few platforms I used, but likely on most of them, creating 
a directory "atomically" ought to be safe.  Yet, this might be a bit 
heavy-weighted when locks are meant to be light and quick.

If you want some more sophistication, leave a file within the lock 
directory (once you successfully created it and so, acquired the lock),
telling who you are.  Destroy the file before destroying the directory 
(of course).  More typically on Unix, put in this file the id of the 
running process, so when creating the directory fails, the attempter may
look in the file, and if there is no such process running, consider the 
lock stale, and preempt it (to do this safely requires some thinking).

François Pinard   http://pinard.progiciels-bpi.ca

More information about the R-devel mailing list