gpt4 book ai didi

multithreading - Perl线程共享二维数组

转载 作者:行者123 更新时间:2023-12-03 13:20:40 25 4
gpt4 key购买 nike

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

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com