Perl内置的哪些功能是原子的? [英] What perl built in functions are atomic?

查看:83
本文介绍了Perl内置的哪些功能是原子的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing some threaded code and I'm wondering what Perl built in functions and operators are atomic and safe to use on a shared variable without locking. For example, I've been told ++, --, += and the like are not because they are implemented as two operations.

在某处有清单吗?

谢谢.

推荐答案

指南:如果这是tie支持的操作,则是原子的.否则,不是.

Guideline: If it's an operation supported by tie, it's atomic. Otherwise, it's not.

控制:

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

这篇关于Perl内置的哪些功能是原子的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆