我正在编写一些线程代码,我想知道Perl内置的函数和运算符是原子的,可以安全地在没有锁定的共享变量上使用。例如,我被告知++
,--
,+=
等不是因为它们是作为两个操作实现的。
某处有名单吗?特别是共享数组原子上的push
,pop
,shift
,unshift
和splice
?
感谢。
答案 0 :(得分:6)
指南:如果是tie支持的操作,它是原子的。否则,它不是。
控制:
use strict;
use warnings;
use feature qw( say );
use threads;
use threads::shared;
use constant NUM_THREADS => 4;
use constant NUM_OPS => 100_000;
my $q :shared = 0;
my @threads;
for (1..NUM_THREADS) {
push @threads, async {
for (1..NUM_OPS) {
++$q;
}
};
}
$_->join for @threads;
say "Got: ", $q;
say "Expected: ", NUM_THREADS * NUM_OPS;
say $q == NUM_THREADS * NUM_OPS ? "ok" : "fail";
输出:
Got: 163561
Expected: 400000
fail
push @a, 1;
代替++$q
:
Got: 400000
Expected: 400000
ok