[Gambas-user] How to lock a file

Benoit Minisini gambas at ...1...
Tue Oct 7 16:51:21 CEST 2008


On mardi 07 octobre 2008, nando wrote:
> There is a problem with your method.
> Between the execution of the KILL and the CREATION of the file,
> multitasking happens and another task could create the file just before
> the original thread executed the CREATE.
>
> In different words, if the first thread lost the CPU just after the KILL
> command due to multitasking and a second thread began the WHILE condition,
> the WHILE would not execute because the WHILE condition fails and
> then the file is CREATED with the user of the second thread.
> Then, multitasking happens and the second thread loses the CPU and the
> first thread continues and it will then create the file destroying the
> second threads information.  Anything could happen in a multitasking
> environment.
>
> I use directories because folder creation is a one-step process there isn't
> time between the two steps for
> another task to steal the lock in betweem code statements.
> An example is something like...
>
> 'create lock, this can be in a SUB with tje folder name passed in
>
> counter=100     '100 loops of 0.1 sec = 10 seconds max to try lock
> flag = FALSE
> WHILE flag = FALSE
>   TRY MKDIR "lock-folder-name"
>   IF ERROR THEN  'it failed
>     flag=TRUE
>     error.clear
>     WAIT 0.1
>     dec counter
>     if counter<=0 then
>       'you could say the the lock took too long
>       'you could allow a user choice to retry or blindly continue.
>       break   'we will assume something is locked too long
>     endif
>   else
>     flag=FALSE
>   endif
> wend
>
>
> 'unlock, this can be a SUB too
> TRY RMDKR "lock-folder-name"
> error.clear
>
> You don't need to know who has the lock because only a successful lock
> leads to code writing some important information for the thread that
> successfully locked.  The unlock must follow very shortly thereafter to
> release the lock and cannot hog the lock.
>
> -Fernando
>

Or better method: use the LOCK / UNLOCK instruction!

-- 
Benoit Minisini




More information about the User mailing list