你如何在 Perl 线程中使用数组引用?
How do you use array refs in Perl threads?
我想在线程中保留带有数组引用的散列。我收到以下错误。
下面的代码是可以执行的。您将看到类似
的错误消息
Invalid value for shared scalar at ./thread1.pl line 25.
#!/usr/bin/env perl
use v5.18;
use strict;
use warnings;
use Data::Dumper;
use threads;
use threads::shared;
my %myhash :shared;
my $stop_myfunc :shared = 0;
my $count = 0;
my $listref;
my @a = ('1','2');
@$listref = @a;
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
sub my2ndfunc {
print "I am in the thread\n";
$count++;
$myhash{$count} = 0;
}
sub myfunc {
while ($stop_myfunc == 0) {
sleep(1);
my2ndfunc();
}
}
my $my_thread = 0;
$stop_myfunc = 0;
$my_thread = threads->create('myfunc');
$myhash{'test'} = 0;
sleep(3);
print Dumper \%myhash;
$stop_myfunc = 1;
$my_thread->join();
1;
我尝试将数组引用声明为 :shared
,但没有帮助。
这里有什么我遗漏的吗?我在这里想不出任何其他选择。感谢任何帮助。
Shared variables can only store scalars, refs of shared variables, or refs of shared data
您必须使用 shared_clone
才能使用任何其他数据类型。
my @a = ('1','2');
my $listref = shared_clone(\@a);
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
由于您可能不需要您共享的数据结构的原始副本,因此最好首先在 shared_clone
语句中定义它。
my %myhash :shared = (
rootdir => "<path>/junk/perl",
listref => shared_clone( ['1', '2'] ),
inventory => shared_clone( { additional => [qw/pylons doritos mountain_dew/] ),
);
我想在线程中保留带有数组引用的散列。我收到以下错误。
下面的代码是可以执行的。您将看到类似
的错误消息Invalid value for shared scalar at ./thread1.pl line 25.
#!/usr/bin/env perl
use v5.18;
use strict;
use warnings;
use Data::Dumper;
use threads;
use threads::shared;
my %myhash :shared;
my $stop_myfunc :shared = 0;
my $count = 0;
my $listref;
my @a = ('1','2');
@$listref = @a;
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
sub my2ndfunc {
print "I am in the thread\n";
$count++;
$myhash{$count} = 0;
}
sub myfunc {
while ($stop_myfunc == 0) {
sleep(1);
my2ndfunc();
}
}
my $my_thread = 0;
$stop_myfunc = 0;
$my_thread = threads->create('myfunc');
$myhash{'test'} = 0;
sleep(3);
print Dumper \%myhash;
$stop_myfunc = 1;
$my_thread->join();
1;
我尝试将数组引用声明为 :shared
,但没有帮助。
这里有什么我遗漏的吗?我在这里想不出任何其他选择。感谢任何帮助。
Shared variables can only store scalars, refs of shared variables, or refs of shared data
您必须使用 shared_clone
才能使用任何其他数据类型。
my @a = ('1','2');
my $listref = shared_clone(\@a);
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
由于您可能不需要您共享的数据结构的原始副本,因此最好首先在 shared_clone
语句中定义它。
my %myhash :shared = (
rootdir => "<path>/junk/perl",
listref => shared_clone( ['1', '2'] ),
inventory => shared_clone( { additional => [qw/pylons doritos mountain_dew/] ),
);