[Gambas-user] Locking files - best method

Rolf-Werner Eilert eilert-sprachen at ...221...
Mon Feb 16 08:33:12 CET 2009


Benoît Minisini schrieb:
>> Sharing a file exclusively locked very briefly and getting everything
>> to work correctly amongst multiple programs can be brain-twisting.
>> With increasing use of mulit-cores, the possibility for sharing files
>> using any lock technique is more important than ever before
>> because all associated programs can execute simultaneously.
>>
> 
> You can use the LOCK/UNLOCK commands and a specific void file on the disk to 
> create system exclusive sections in your code.
> 
> Let's suppose you want to modify a file named "/tmp/foo".
> 
> ...
> DIM hLock AS Stream
> DIM hFile AS Stream
> 
> ' Try to acquire the lock
> TRY hLock = LOCK "/tmp/foo.lock"
> IF ERROR THEN
>   PRINT "'foo' is being modified. Try again later."
>   RETURN
> ENDIF
> 
> ' Lock was acquired, you can modify the file now!
> hFile = OPEN "/tmp/foo" FOR OUTPUT
> ...
> CLOSE #hFile
> 
> ' Do not forget to release the lock
> UNLOCK hLock
> ...
> 

IMHO "the one" drawback remains: foo.lock isn't foo. You cannot lock the 
file itself, relying on the operating system / the file system to really 
make sure nobody else is able to corrupt your file during your access.

If there's some other app that doesn't care about .lock files, your 
/tmp/foo will be lost. Of course, the same applies to my own methods 
like lock directories or self-made lock files.


The only way to solve this would be a mechanism in the file system 
itself, giving the opportunity to code something like

hFile = OPEN "/tmp/foo" FOR OUTPUT LOCK

which would unlock the file automagically when you CLOSE it (or the 
instance of your application ends).

Regards

Rolf




More information about the User mailing list