它的主要目的是多线程。它锁定一个共享变量,如果其他线程尝试lock
它,那么lock
调用将被阻塞,直到它被释放。
举例说明:
#!/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);
#lock released when out of scope.
}
for (1..10) {
threads -> create (\&worker_thread);
}
foreach my $thr (threads -> list) {
$thr -> join();
}
您可以使用它的资源控制,以创建互斥,或者你可以用它来锁定例如当你想在没有另一个线程同时进行更新时使用散列。
虽然您应该注意 - lock
未执行。尽管有lock
,您仍然可以修改共享变量。只有lock
函数调用才会测试变量当前是否已解锁。
当您进行可变操作时,使用lock
很重要。任何测试,如果你不锁定你可以创建竞争条件 - 你不能确定在读写之间,另一个线程不会做同样的事情。
你可能也想看看Thread::Semaphore
它做了类似的事情。
请参阅[此主题](http://www.perlmonks.org/?node_id=579444)了解一些信息 – Andrei 2014-08-29 16:29:42