in reply to Tk + threads
The "while(<$pipe>)" is not good in gui programming. You should look at Tk::fileevent, and try to design using it. It allows you to watch filehandles in a non-blocking manner.
When using Tk and threads, it is best to use Tk only in your main thread, to display what is going on in the worker threads. In the worker thread, don't access the Tk display widgets, rather pass the data back to the main thread thru a Tk timer and shared variables.
#!/usr/bin/perl use strict; use Tk; use threads; use threads::shared; my $data_out:shared = ''; my $data_in:shared = ''; my $thread_die = 0; #create the thread before you start any Tk so the #thread dosn't get any Tk stuff copied in my $wthr = threads->new( \&update_thread )->detach; create_tk_window(); exit; ######################################################### #the non-Tk worker code sub update_thread { print "update_thread called...\n"; while (1) { if($thread_die == 1){return} $data_in = 'thread-processing'.$data_out; sleep 1; } END: } ######################################################### sub create_tk_window { my $mw = MainWindow->new( -background => 'black', -foreground => 'yellow', -title => "Thread Test" ); $mw->geometry("600x400"); $mw->minsize( 400, 400 ); $mw->maxsize( 800, 800 ); my $sent_text = $mw->Scrolled('Text', -height => 10, -width => 60, -background => 'black', -foreground => 'yellow' )->pack( -side => 'bottom', -anchor => 's', -pady => 2 ); my $received_text = $mw->Scrolled( "Text", -height => 10, -width => 60, -background => 'white', -foreground => 'black', )->pack(); my $repeater; $mw->Button(-text=> 'Exit', -command => sub{ $thread_die = 1; $repeater->cancel; $mw->withdraw; kill 9, $$; })->pack; $repeater = $mw->repeat(1000, sub{ $data_out++; $sent_text->insert( 'end', "Sent $data_out\n" ); $sent_text->see('end'); $received_text->insert( 'end', "Received $data_in\n" ); $received_text->see('end'); }); MainLoop; }
|
|---|