Sch*_*ern 8 perl multithreading
我正在写一些线程代码,我想知道Perl内置的函数和运算符是原子的,可以安全地使用共享变量而不需要锁定.例如,有人告诉我++,--,+=等等是不是因为他们是作为两个操作来实现.
某个地方有名单吗?特别地是push,pop,shift,unshift和splice一个共享的阵列原子上?
谢谢.
指南:如果它是由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";
Run Code Online (Sandbox Code Playgroud)
输出:
Got: 163561
Expected: 400000
fail
Run Code Online (Sandbox Code Playgroud)
push @a, 1;而不是++$q:
Got: 400000
Expected: 400000
ok
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
871 次 |
| 最近记录: |