This is the main goal for multithreading. It locks the shared variable, so if any other thread tries to execute lock , then the lock call is blocked until it is released.
To illustrate:
#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; my $lock_var : shared; sub worker_thread { print threads -> self -> tid(). ": Waiting for lock\n"; lock ( $lock_var ); print threads -> self -> tid(). ": got lock, doing some pretend code\n"; sleep rand(10);
You can use it to manage resources to create a mutual exception, or you can use it to block, for example. hash when you want to update it without using another thread, doing it at the same time.
It should be noted that - lock not applicable. You can still change the shared variable, despite the lock . This is just a call to the lock function, which will check if the variable is currently unlocked.
When you perform variable manipulation, it is important to use lock . Any test in which you read->change->write can create a race condition, if you don’t block it, you cannot be sure that between reading and writing another thread will not do the same.
You can also see Thread::Semaphore , which does something similar.
source share