gpt4 book ai didi

multithreading - 如何在Perl中唤醒线程

转载 作者:行者123 更新时间:2023-12-03 13:17:57 25 4
gpt4 key购买 nike

有什么方法可以在Perl中使用其线程ID来唤醒 sleep 线程?提前致谢

以下是我尝试使用暂停和恢复的内容

use warnings;
use strict;
use threads;
use threads::shared;
use Thread::Suspend;

my $val:shared = 0;
my $count = 0;
while ( $count < 4 )
{
my $thr = threads->create( \&worker );
$count++;
}

use Tk;
my $mw = MainWindow->new();
$mw->protocol('WM_DELETE_WINDOW' => sub { &clean_exit });
my $thr;
my $button;
$button = $mw->Button(
-text => 'Invoke thread',
-command => sub{
$val += 1;
if( $val > 4)
{
$val = 1;
}
foreach $thr (threads->list())
{
if( $thr->tid() == $val )
{
$thr->resume();
goto OUTSIDE;
}
}
OUTSIDE:
})->pack();

MainLoop;

sub clean_exit
{
my @running_threads = threads->list;
if (scalar(@running_threads) < 1)
{
print "\nFinished\n";
exit;
}
else
{
foreach my $thr (threads->list())
{
$thr->kill('KILL')->detach();
}
exit;
}
}

sub worker
{
$SIG{'KILL'} = sub { threads->exit(); };
threads->suspend();
print threads->tid()."\n";
}

我正在尝试做的是,当用户单击“调用”按钮时,它应基于$ val恢复线程。但是它不能那样工作。 ID为4的第一个线程是单击4而不是1之后的恢复线程。请帮助调试代码。 P.S.我是Perl的新手

最佳答案

#!/usr/bin/perl
use warnings;
use strict;
use threads;
use threads::shared;
use Thread::Suspend;

my $val:shared = 0;
my $count = 0;
my @thr;

while ( $count < 4 )
{
$thr[$count] = threads->create( \&worker, $count );
$count++;
}

use Tk;
my $mw = MainWindow->new();
$mw->protocol('WM_DELETE_WINDOW' => sub { &clean_exit });
my $button;
$button = $mw->Button(
-text => 'Invoke thread',
-command => sub{
foreach my $th (@thr)
{
print "Resuming...\n";
$th->resume();
}
})->pack();

MainLoop;

sub clean_exit
{
my @running_threads = threads->list;
if (scalar(@running_threads) < 1)
{
print "\nFinished\n";
exit;
}
else
{
foreach my $th (@thr)
{
$th->kill('KILL')->detach();
}
exit;
}
}

sub worker
{
my($id)=@_;
$SIG{'KILL'} = sub { print "Die...\n";threads->exit(); };
threads->self->suspend();
print "Worker:Resuming....\n";
while(1){
print threads->tid()." $id\n";
sleep(1);
}
}

关于multithreading - 如何在Perl中唤醒线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6001260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com