See Original text in context
multi method protect(Lock: )
Obtains the lock, runs &code
, and releases the lock afterwards. Care is taken to make sure the lock is released even if the code is left through an exception.
Note that the Lock itself needs to be created outside the portion of the code that gets threaded and it needs to protect. In the first example below, Lock is first created and assigned to $lock
, which is then used inside the Promise to protect the sensitive code. In the second example, a mistake is made: the Lock
is created right inside the Promise, so the code ends up with a bunch of separate locks, created in a bunch of threads, and thus they don't actually protect the code we want to protect.
# Right: $lock is instantiated outside the portion of the# code that will get threaded and be in need of protectionmy = Lock.new;await ^20 .map:# !!! WRONG !!! Lock is created inside threaded area!await ^20 .map:
See Original text in context
method protect(Lock::Async: )
This method reliably wraps code passed to &code
parameter with a lock it is called on. It calls lock
, does an await
to wait for the lock to be available, and reliably calls unlock
afterwards, even if the code throws an exception.
Note that the Lock::Async itself needs to be created outside the portion of the code that gets threaded and it needs to protect. In the first example below, Lock::Async is first created and assigned to $lock
, which is then used inside the Promise
code to protect the sensitive code. In the second example, a mistake is made, the Lock::Async
is created right inside the Promise
, so the code ends up with a bunch of different locks, created in a bunch of threads, and thus they don't actually protect the code we want to protect. Modifying an Array simultaneously from different in the second example is not safe and leads to memory errors.
# Compute how many prime numbers there are in first 10 000 of them# using 50 threadsmy = 0 .. 10_000;my ;my ;# Right: $lock is instantiated outside the portion of the# code that will get threaded and be in need of protection,# so all threads share the lockmy = Lock::Async.new;for ^50 -># await for all threads to finish calculationawait Promise.allof();# say how many prime numbers we foundsay "We found " ~ .grep(*.value).elems ~ " prime numbers";
The example below demonstrates the wrong approach: without proper locking this code will work most of the time, but occasionally will result in bogus error messages or low-level memory errors:
# !!! WRONG !!! Lock::Async is instantiated inside threaded area,# so all the 20 threads use 20 different locks, not syncing with# each otherfor ^50 ->