multithreading - Perl线程共享二维数组

标签 multithreading perl

如何共享二维数组,以便在线程中进行更改,然后在另一个线程中进行更改?
谢谢

    our @Cells=(); 
    share(@Cells); 
    for $Row_Of_Cell (0..$Number_Of_Rows-1) { 
            $Cells[$Row_Of_Cell]=&share([]); 
            for $Column_Of_Cell (0..$Number_Of_Columns-1) {
                    $Cells[$Row_Of_Cell][$Column_Of_Cell]=0; 
            } 
    } 

是对的吗?

最佳答案

您还必须使用shareshared_clone共享内部结构:

#!/usr/bin/perl
use warnings;
use strict;

use threads;
use threads::shared;

my @ar2d : shared;
my @second : shared = qw/A B C D/;
@ar2d = ( shared_clone([qw/a b c d/]),
          \@second,
        );

my $thread = sub {
    my $idx = shift;
    while ('c' eq lc $ar2d[$idx][2]) {
        print "In thread1 $ar2d[$idx][2]\n";
        sleep 1;
    }
};


my $thread1 = threads->create($thread, 0);
my $thread2 = threads->create($thread, 1);

for (1 .. 5) {
    sleep 1;
    print "In main $ar2d[0][2] $ar2d[1][2]\n";
}
$ar2d[0][2] = 'x';
$ar2d[1] = shared_clone([qw/A B X D/]);
print "In main $ar2d[0][2] $ar2d[1][2]\n";

$thread1->join;
$thread2->join;

关于multithreading - Perl线程共享二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16142374/

相关文章:

c++ - 确保线程已启动 winapi c++

java - 维护拥有大量线程的 Java 应用程序时,我需要了解什么?

java - 如何在多线程环境中共享2个SSH连接

php - 为数据库表自动生成 CRUD UI 的应用程序

perl - Mojolicious和Moose在一起玩得好吗?

java - synchronized vs ReentrantLock 无竞争锁

java - 如何编写一个函数来并行查找大于 N 的值

perl - PersistentPerl 或 SpeedyCGI 的替代品有哪些?

perl - 是否有一种自动方法来发现与 Embperl 2.x 不兼容的 Embperl 1.x 语法?

perl - 如何在磁盘上而不是在 RAM 中保存大哈希值?