method protect

Documentation for method protect assembled from the following types:

class Lock

From Lock

(Lock) method protect

Defined as:

method protect(Lock:D: &code)

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 Promises 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 protection 
my $lock = Lock.new;
await ^20 .map: {
    start {
        $lock.protect: {
            print "Foo";
            sleep rand;
            say "Bar";
        }
    }
}
 
# !!! WRONG !!! Lock is created inside threaded area! 
await ^20 .map: {
    start {
        Lock.new.protect: {
            print "Foo"sleep randsay "Bar";
        }
    }
}

class Lock::Async

From Lock::Async

(Lock::Async) method protect

Defined as:

method protect(Lock::Async:D: &code)

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 Promises 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 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 protection 
my $lock = Lock::Async.new;
await ^20 .map: {
    start {
        $lock.protect: {
            print "Foo";
            sleep rand;
            say "Bar";
        }
    }
}
 
# !!! WRONG !!! Lock::Async is instantiated inside threaded area! 
await ^20 .map: {
    start {
        my $lock = Lock::Async.new;
        $lock.protect: {
            print "Foo"sleep randsay "Bar";
        }
    }
}