Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Do I need threading for my GUI?

by shmem (Chancellor)
on Feb 18, 2008 at 11:06 UTC ( [id://668511]=note: print w/replies, xml ) Need Help??


in reply to Do I need threading for my GUI?

A trick to avoid this is giving back control to the Tk main loop. This can either be done by splitting up the "mainprocess" into singular tasks which call each other e.g. via Tk->after, or storing that main-processes state somehow, thus making it re-entrant. You could also use the POE framework to do either of those.

Term::ReadLine::Gnu uses another trick, it calls the Tk event handler DoOneEvent() directly - with due care, because it blocks if there's no event dispatched. If the above techniques (or just the use of POE) aren't feasible, you could use that trick.

See Tk::Event.

update:

The proffered solution... Clock that goes backwards enhanced with a CPU-intensive, long running task. While the task is as silly as the clock itself, it is suitable for the POC.

It's just a matter of adding a signal handler and calling the event dispatcher in a non-blocking way.

#!/usr/bin/perl use strict; use Time::HiRes qw(ualarm); use Tk; BEGIN {*Tk::Clock::time = sub { time * -1 } } use Tk::Clock; my $wm = MainWindow->new; my $ck = $wm->Clock->pack(-side => 'top'); my $b = $wm->Button(-text => 'Start Process', -command => \&mainproce +ss)->pack; $ck->config(dateFormat => "dd-mm-yyy"); MainLoop; # # simulate a long running, CPU-intensive task # sub mainprocess { local $SIG{ALRM} = sub { DoOneEvent(Tk::Event::DONT_WAIT); ualarm(1000); } ualarm(1000); # task body begin my $c; $b->configure(-text => 'running...'); while (1) { $c++; print $c,"\n" unless $c % 1000; last if $c == 10000000; } $b->configure(-text => 'Start Process'); # task body end ualarm(0); }

Pretty few lines of code added... well, I could shoehorn the alarm handler into one line, and it would be 3 lines - not counting the 'use Time::HiRes' line ;-)

I guess it's not necessary to offer a code conversion job for something that simple.

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://668511]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-24 23:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found