perl内置的函数是原子的吗?

时间:2012-10-23 22:30:26

标签: multithreading perl

我正在编写一些线程代码,我想知道Perl内置的函数和运算符是原子的,可以安全地在没有锁定的共享变量上使用。例如,我被告知++--+=等不是因为它们是作为两个操作实现的。

某处有名单吗?特别是共享数组原子上的pushpopshiftunshiftsplice

感谢。

1 个答案:

答案 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
相关问题