multithreading - 线程 perl 中未锁定的共享哈希操作安全性

标签 multithreading perl race-condition

问题

多个线程在 shared 中获取和存储简单的独立值是否安全?没有 lock() 哈希?

你能证明它或引用强大的权威吗?

背景

我认为,在最坏的情况下,未锁定的哈希操作可能会导致段错误。

但是,我最近看到代码以这种方式协调工作线程的事件,作者认为这种方式是安全的。有问题的代码仅执行简单的提取和存储:

  • 共享哈希是一个普通的共享哈希(不是用户定义的 tie()d 构造)
  • 这些值是简单的标量,不是引用,也不是共享的
  • 每个键/值对都由一个线程唯一存储和修改
  • 所有键/值对都可以被任何线程获取
  • 没有线程遍历共享哈希(没有each(),没有keys(),也没有values()循环)

代码摘录

my %status : shared;

for my $id (1 .. $n) {
  threads->create(\&thread_routine);
}

sub thread_routine {
  my $me = threads->tid();

  $status{ $me } = 'Getting ready';
  ... do something ...
  $status{ $me } = 'Thinking';
  ... do something else ...

  $status{ $me } = 'Looking around';
  for my $tid (threads->list) {
    next if $tid == $me;
    if ($status{ $tid } eq "Thinking") { ... react ... }
    ...
  }

  $status{ $me } = 'All done';
}

最佳答案

这是权威答案。来自perlthrtut , 在“共享和非共享数据”的末尾,

Note that a shared variable guarantees that if two or more threads try to modify it at the same time, the internal state of the variable will not become corrupted. However, there are no guarantees beyond this, as explained in the next section.

因此,是的,在没有锁定的情况下在散列中存储和获取简单的单个值是安全的。

关于multithreading - 线程 perl 中未锁定的共享哈希操作安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3452001/

相关文章:

android - 如何判断哪些线程产生了所有垃圾?

java - 下面的程序有什么问题?Java wait/notify 不起作用

Perl LWP::useragent 捕获服务器响应 header

c# - 等同于 Java 中的 C# 锁?

java - 哪个线程在并发线程中首先完成?

perl - 如何在 Perl CGI 中处理元素值?

Perl substr(STRING, @ARRAY) ne substr(STRING, OFFSET, LENGTH)?

multithreading - OpenCL float 减少

c++ - 必须将互斥锁用于数组中的 "get"值吗?

javascript - 通过 knex 迁移 promise 所有竞争条件