Perl 错误:线程无法启动:共享标量的值无效 [英] Perl Error: thread failed to start: Invalid value for shared scalar
问题描述
尝试运行我的测试代码时出现以下错误:
I get the following error when trying to run my test code:
线程无法启动:./threaded_test.pl 第 47 行的共享标量值无效.
第 47 行是:%hoh = hoh(@new_array);
我的观察:
- 如果我删除了第 47 行和其他引用
%hoh
的行,那么脚本运行时不会出错 - 我可以创建一个新的散列
%new_hash = (itchy => "Scratchy");
没有错误,但是当我尝试从另一个子节点返回"一个散列时(第 47 行),它导致上述错误.
- If I remove line 47 and other lines referencing
%hoh
, then the script runs without errors - I can create a new hash
%new_hash = (itchy => "Scratchy");
without errors, but when I try to "return" a hash from another sub (line 47), it results in the error above.
不幸的是,我无法使用输入/输出队列,因为我使用的 Thread::Queue 版本太旧(并且安装在我无法控制的系统上)并且不支持 hash 和 hash-ref 类型通过队列返回(根据 this).显然,我的版本只支持通过队列返回的字符串.
Unfortunately, I cannot use a in/out Queue because the version of Thread::Queue that I use is too old (and installed on a system I have no control over) and doesn't support hash and hash-ref types to be returned via a Queue (according to this). Apparently, my version only support strings to be returned via queues.
有没有办法成功做到这一点:$hash{$string}{"jc"} = \%hoh;
Is there a way to successfully do this: $hash{$string}{"jc"} = \%hoh;
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use Thread::Queue;
use constant NUM_WORKERS => 10;
my @out_array : shared = ();
main();
sub main
{
my @results = test1();
foreach my $item (@results) {
print "item: $item\n";
}
}
sub test1
{
my $my_queue = Thread::Queue->new();
foreach (1..NUM_WORKERS) {
async {
while (my $job = $my_queue->dequeue()) {
test2($job);
}
};
}
my @sentiments = ("Axe Murderer", "Mauler", "Babyface", "Dragon");
$my_queue->enqueue(@sentiments);
$my_queue->enqueue(undef) for 1..NUM_WORKERS;
$_->join() for threads->list();
my @return_array = @out_array;
return @return_array;
}
sub test2
{
my $string = $_[0];
my %hash : shared;
my @new_array : shared;
my %new_hash : shared;
my %hoh : shared;
@new_array = ("tom", "jerry");
%new_hash = (itchy => "Scratchy");
%hoh = hoh(@new_array);
my %anon : shared;
$hash{$string} = \%anon;
$hash{$string}{"Grenade"} = \@new_array;
$hash{$string}{"Pipe bomb"} = \%new_hash;
$hash{$string}{"jc"} = \%hoh;
push @out_array, \%hash;
return;
}
sub hoh
{
my %hoh;
foreach my $item (@_) {
$hoh{"jeepers"}{"creepers"} = $item;
}
return %hoh;
}
推荐答案
问题在于您试图存储对共享变量中未共享的内容的引用.您需要使用前面提到的share
,或者您需要序列化数据结构.
The problem is that your trying to store a reference to something that isn't shared in a shared variable. You need to use share
as previously mentioned, or you need to serialise the data structure.
这篇关于Perl 错误:线程无法启动:共享标量的值无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!