in reply to Executing functions in Perl::Tk

liverpole's thread example is pretty good, but for many reasons you really don't want to launch a thread for something as simple as a non-blocking execution of a function.

For instance, the code in liverpole's example

sub button_press { my $sthread = threads->new(sub { worker_thread() }); $sthread->detach(); # Here we "return immediately" :) return; }
where the thread is created in a button callback, after Tk code has been invoked in main, has a possible problem. Many nodes have been posted previously, on how some of the "copy-on-write" Tk code gets copied into the thread, and sometimes causes "free to wrong pool" errors. The example works, but it is a very simple button press. I'm just saying, beware of the non-thread-safety of the Tk module. The general advice to absolutely avoid the possible problem, is shown in PerlTk on a thread....... the copy-on-write thread action combined with the non-thread safety of Tk, means you need to follow alot of restrictions for foolproof operation of your Tk-threaded program.

However, threads aside, if you just want to execute something and move on, you can fork it off with a piped open, IPC::Open3, etc. Then use Tk::fileevent, or i used a timer in the first code block, to read the results as they come back in.

#!/usr/bin/perl use warnings; use strict; use Tk; my $mw = MainWindow->new(-background => 'gray50'); my $text = $mw->Scrolled('Text')->pack(); my $pid; my $startb = $mw->Button( -text => 'Start', -command=> \&work, )->pack(); my $count = 0; my $label = $mw->Label(-textvariable=>\$count)->pack(); my $testtimer = $mw->repeat(500, sub { $count++} ); my $stopb = $mw->Button( -text => 'Exit', -command=>sub{ kill 9,$pid; exit; }, )->pack(); MainLoop; ##################################### sub work{ $startb->configure(-state=>'disabled'); use Fcntl; + my $flags; + #long 10 second delay between outputs $pid = open (my $fh, "top -b -d 10 |" ) or warn "$!\n"; fcntl($fh, F_SETFL, O_NONBLOCK) || die "$!\n"; # Set the non-block f +lags my $repeater; $repeater = $mw->repeat(10, sub { if(my $bytes = sysread( $fh, my $buf, 1024)){; $text->insert('end',$buf); $text->see('end'); } } ); }

and reading with a fileevent

#!/usr/bin/perl use warnings; use strict; use IPC::Open3; use Tk; $|=1; my $pid=open3(\*IN,\*OUT,0,'/bin/bash'); my $mw=new MainWindow; $mw->geometry("600x400"); my $t=$mw->Scrolled('Text',-width => 80, -height => 80, )->pack; &refresh; $mw->fileevent(\*OUT,'readable',\&write_t); my $id = Tk::After->new($mw,2000,'repeat',\&refresh); MainLoop; sub refresh{ print IN "top b n 1"; print IN "\n"; #absolutely needed and on separate line } sub write_t { my $str= <OUT>; $t->insert("1.0",$str); # $t->see("0.0"); } __END__

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku