lock. Exclusive use of code

^file:lock[file_to_be_locked]{code}

Code is not simultaneously executed by multiple visitors. File_to_be_locked is used to ensure exclusive use.

Example
^file:lock[/counter.lock]{ 
    $file[^file::
load[text;/counter.txt]]
    $string[^
eval($file.text+1)]
    ^string.
save[/counter.txt]
}
Number of visitors$string<br />

If locking is not used, two simultaneous requests can increase the counter's value... by 1, not by 2:
·first visitor comes;  
·second visitor comes;  
·first visitor reads counter's value-value equals 0;  
·second visitor reads counter's value-value equals 0;  
·first visitor increases counter's value-value now equals 1;  
·second visitor increases counter's value-value now equals 1;  
·first visitor writes new value-1;  
·second visitor writes new value immediately after the first visitor, the value is 1, not 2.  

Note: you should always keep in mind simultaneous requests. If you work with databases, SQL-servers usually have built-in means that provide correct processing for simultaneously incoming requests.

Note: when there are more then one lock, always analize there mutual relations to avoid "A waits B, B waits A", so called deadlock situation.



Copyright © 1997–2021 Art. Lebedev Studio | http://www.artlebedev.com Last updated: 21.09.2007