multithreading - 从线程访问包变量

标签 multithreading perl signals

我在从线程访问包变量时遇到问题。这是一个大项目,所以我将尝试提取代码的相关部分。

我将线程模块和 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/

相关文章:

linux - 如何只替换 Perl 中 IP 地址的前三个八位字节

perl - 如何获得 Perl 中的调用堆栈列表?

java - sun.misc.Signal 的替代品

java - java中繁忙的等待线程

multithreading - 如何通过 tomcat 8 中的 java 代码动态设置系统属性(而不是通过 tomcat 配置文件)

java - 用线程获取素数。如何划分区间?

perl - 如何在 sed 中包含 perl 命令?

python - mousepress事件的问题

matlab - 频率增加的 Simulink 正弦波

java - JPA:读取并坚持一个事务,同时阻塞不同线程中的读取