Saturday, May 8, 2010

Perl Tkx Thread request demo


#!/usr/bin/perl -w
use strict;
use warnings;
use threads;
use threads::Shared;
use Tkx;

#Create shared variables
my $child_finished_flag: shared = 0;
my $child_request_flag: shared = 0;

#Create child thread
my $ChildThread = threads->create( \&child_thread );
$ChildThread->detach();

#Create Tkx mainwindow
my $mw = Tkx::widget->new(".");
my $frame2 = $mw -> new_ttk__frame(-borderwidth => 2);
$frame2->g_pack(-anchor => 'nw', -padx => '10', -pady => '10');

#create progressbar and button widgets
my $progressbar = $frame2->new_ttk__progressbar(-orient => 'horizontal', -length => 200, -mode => 'determinate');
my $button = $frame2->new_ttk__button(-text => "Process Request", -style => "Bold.TButton", -state => 'normal', -width => '15', -command => [\&process_request] );
$button->g_grid(-row=>1, -column=>1, -columnspan=>2, -padx=>10, -pady=>5);
$progressbar->g_grid(-row=>2, -column=>1, -columnspan=>2, -padx=>10, -pady=>5);

#Initiate Tkx Listener
Tkx::MainLoop();

sub process_request {
$progressbar->start();
$child_request_flag = 1;
& check_status_1;
}

sub check_status_1 {
Tkx::after(500, sub {
if ($child_finished_flag == 1) {
$progressbar->stop();
#Reset flags
$child_finished_flag = 0;
$child_request_flag = 0;
print "child_request finished\n";
}
else {
& check_status_2;
print "child_request processing\n";
}
});
}



sub check_status_2 {
Tkx::after(500, sub {
& check_status_1;
});
}

sub child_thread {
while (1) {
sleep 2;
if ($child_request_flag == 1) {
print "begin child_request\n";
## backtick command here
my @ping=`ping www.yahoo.com`;
open (CONFIG, '>ping_result.txt');

foreach my $pingtext (@ping) {
print CONFIG $pingtext;
}
close (CONFIG);
$child_finished_flag=1;
}
else {print "waiting for child_request\n";}
}
}

1 comment: