#!/usr/local/bin/perl -w use Tk; use threads; use threads::shared; ############# ## Globals ## ############# my $shared_text: shared = ""; # The message sent back to the parent my $shared_flag: shared = 0; # 0 = no msg waiting, 1 = msg waiting ################## ## Main program ## ################## my $pthread = threads->new(\&worker_thread); $pthread->detach(); my $mw = MainWindow->new(); my $text = $mw->Entry(-width => 8)->pack(); $text->insert(0, 'abcde'); my $button = $mw->Button(-text=>'click', -command => \&talk_to_worker)->pack(); MainLoop; ################# ## Subroutines ## ################# # Parent subroutines sub talk_to_worker{ while (0 == $shared_flag) { print "(parent) Waiting for flag to go to 1\n"; select(undef, undef, undef, 0.5); } my $msg = $shared_text; print "(parent) Got message '$msg'\n"; if ($msg) { $text->delete('0.0', "end"); $text->insert('0.0', $msg); $mw->update(); } print "(parent) Resetting flag to 0\n"; $shared_flag = 0; } # Worker subroutines sub worker_thread { for my $i (0..100) { sleep 3; send_message_to_parent("-$i"); } } sub send_message_to_parent { my ($msg) = @_; # Wait until the $shared_flag is zero again while (1 == $shared_flag) { print "(worker) Waiting for flag to go to 0\n"; select(undef, undef, undef, 0.5); } # Send the message; $shared_text = $msg; # Raise the flag to handshake with the parent $shared_flag = 1; }