In Lock::Async§

See primary documentation in context for method lock

method lock(Lock::Async:D: --> Promise:D)

Returns a Promise that will be kept when the lock is available. In the case that the lock is already available, an already kept Promise will be returned. Use await to wait for the lock to be available in a non-blocking manner.

my $l = Lock::Async.new;
await $l.lock;

Prefer to use protect instead of explicit calls to lock and unlock.

In IO::CatHandle§

See primary documentation in context for method lock

method lock(IO::CatHandle:D: Bool:D :$non-blocking = False, Bool:D :$shared = False --> True)

Same as IO::Handle.lock. Returns Nil if the source handle queue has been exhausted.

Locks only the currently active source handle. The .on-switch Callable can be used to conveniently lock/unlock the handles as they're being processed by the CatHandle.

In IO::Handle§

See primary documentation in context for method lock

method lock(IO::Handle:D:
            Bool:D :$non-blocking = False, Bool:D :$shared = False
            --> True)

Places an advisory lock on the file the filehandle if open for. If :$non-blocking is True will fail with X::IO::Lock if lock could not be obtained, otherwise will block until the lock can be placed. If :$shared is True will place a shared (read) lock, otherwise will place an exclusive (write) lock. On success, returns True; fails with X::IO::Lock if lock cannot be placed (e.g. when trying to place a shared lock on a filehandle opened in write mode or trying to place an exclusive lock on a filehandle opened in read mode).

You can use .lock again to replace an existing lock with another one. To remove a lock, close the filehandle or use unlock.

# One program writes, the other reads, and thanks to locks either
# will wait for the other to finish before proceeding to read/write

# Writer
given "foo".IO.open(:w) {
    .lock;
    .spurt: "I ♥ Raku!";
    .close; # closing the handle unlocks it; we could also use `unlock` for that
}

# Reader
given "foo".IO.open {
    .lock: :shared;
    .slurp.say; # OUTPUT: «I ♥ Raku!␤»
    .close;
}

In Lock§

See primary documentation in context for method lock

method lock(Lock:D:)

Acquires the lock. If it is currently not available, waits for it.

my $l = Lock.new;
$l.lock;

Since a Lock is implemented using OS-provided facilities, a thread waiting for the lock will not be scheduled until the lock is available for it. Since Lock is re-entrant, if the current thread already holds the lock, calling lock will simply bump a recursion count.

While it's easy enough to use the lock method, it's more difficult to correctly use unlock. Instead, prefer to use the protect method instead, which takes care of making sure the lock/unlock calls always both occur.