我在从线程访问包变量时遇到问题。这是一个大项目,所以我将尝试提取代码的相关部分。
我将线程模块和 Moose 用于 OO 部分。
our $thread2;
around 'new' => sub {
[...]
threads->create( \&_thread1Func, $shared_self );
if (!$thread2) {
$thread2 = threads->create( \&_thread2Func, $shared_self );
$thread2->detach();
}
}
sub _thread1Func {
$thread2->kill('SIGUSR1');
}
sub _thread2Func {
$SIG{'USR1'} = sub { [...] };
while (1) {
sleep 5;
[...]
}
}
我收到以下错误:
Thread N terminated abnormally: Can't call method "kill" on an undefined value at XXXX.pm line n.
与
n
指向 $thread2->kill('SIGUSR1');
行我在想用
our
声明 $thread2使其从整个包装中可见。知道发生了什么吗?
最佳答案
如 perldoc threads 中所述:
Since Perl 5.8, thread programming has been available using a model called interpreter threads which provides a new Perl interpreter for each thread, and, by default, results in no data or state information being shared between threads.
our
“为当前包中同名的包变量创建词法别名,以在当前词法范围内使用。”这并不意味着它创建了一个在线程之间共享的变量。为此,您需要 threads::shared .但是,请注意:
This module supports the sharing of the following data types only: scalars and scalar refs, arrays and array refs, and hashes and hash refs.
你的代码对我来说看起来很麻烦。如果您解释为什么要这样做,我们可能会提供更具体的帮助。
以下可能会做一些接近你想要的事情:
#!/usr/bin/env perl
use strict;
use warnings;
use threads;
use threads::shared;
my $thread2_tid :shared;
sub myfunc {
threads->create(\&_thread1Func);
if (!$thread2_tid) {
my $thread2 = threads->create(\&_thread2Func);
$thread2_tid = $thread2->tid;
}
}
sub _thread1Func {
while (1) {
next unless defined $thread2_tid;
last if $thread2_tid == -1;
my $thread2 = threads->object($thread2_tid);
$thread2->kill('SIGUSR1');
sleep 1;
}
}
sub _thread2Func {
local $SIG{'USR1'} = sub { print "SIGUSR1 received\n" };
local $| = 1;
while (1) {
sleep 1;
print '.';
if (5 < time - $^T) {
$thread2_tid = -1;
last;
}
}
}
myfunc();
$_->join for threads->list;
关于multithreading - 从线程访问包变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340091/