For Programmers: Free Programming Magazines  


Home > Archive > PerlTk > March 2007 > To destroy thread in perl.









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author To destroy thread in perl.
rajendra

2007-03-09, 4:04 am

Hello All,

How to destroy(command) to the the created thread in perl.


zentara

2007-03-09, 7:03 pm

On Fri, 9 Mar 2007 11:43:17 +0530, "rajendra"
<rajendra.pra@in.bosch.com> wrote:

>Hello All,
>
>How to destroy(command) to the the created thread in perl.
>


You must somehow tell the thread to go to the end of
it's code block, or get it to return.

Usually its done with a shared variable.

If the thread was detached, having it return kills it.
If the thread was not detached, it must return, before
it can be joined.

If you want a complex example see:
http://perlmonks.org?node_id=401819

A simple example is below:
(Note some error checking is left out for simplicity)

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

# declare, share then assign
my $ret;
share $ret;
$ret = 0;
my $die;
share $die;
$die = 0;

my $val = 0;

#create thread before any tk code is called
my $thr = threads->create( \&worker );

use Tk;

my $mw = MainWindow->new();
$mw->protocol('WM_DELETE_WINDOW' => sub { &clean_exit });

my $label = $mw->Label(
-width => 50,
-textvariable => \$val )->pack();

my $button = $mw->Button(
-text => 'Stop thread',
-command => sub{
$die = 1;
$thr->join;
},
)->pack();


my $timer = $mw->repeat(10,sub{
$val = $ret;
});

MainLoop;

sub clean_exit{
$timer->cancel;

my @running_threads = threads->list;
if (scalar(@running_threads) < 1){print "\nFinished\n";exit}
else{
$die = 1;
$thr->join;
exit;
}
}

# no Tk code in thread
sub worker {
for(1..10){
print "$_\n";
$ret = $_;

if($die){return}

sleep 1;
}
$ret = 'thread done, ready to join';
print "$ret\n";
}
__END__




--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com