如何共享二维数组,以便在线程中进行更改,然后在另一个线程中进行更改?
谢谢
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;
}
}
是对的吗?
最佳答案
您还必须使用share
或shared_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/