Reputation: 2605
Is there any way for waking a sleeping thread using its thread ID in Perl ? Thanks in advance
Below is the what I have tried using suspend and resume
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";
}
What I am trying to do is when user click on Invoke button it should resume the thread based on the $val. But its not working in that way. First thread with ID 4 is resume that too after 4 clicks instead of 1. Please help in debugging the code. P.S. I am newbie to Perl
Upvotes: 1
Views: 775
Reputation: 41
#!/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);
}
}
Upvotes: 4