Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: controlling threads with Tk: while loop vs. signals

by BrowserUk (Pope)
on Feb 14, 2012 at 21:41 UTC ( #953775=note: print w/replies, xml ) Need Help??


in reply to controlling threads with Tk: while loop vs. signals

Pairing the clumsy Thread::Semaphore with the should-never-have-been-invented "threads signalling" is an extremely convoluted way of controlling a producer thread.

This does what I think you were trying to achieve -- start the thread 'suspended' and allow it to be resumed and suspended -- with rather less fuss and complication:

#! perl -slw use strict; use threads; use threads::shared; use Thread::Queue; use Tk; my $sem :shared = 0; sub thread { my( $Q, $file ) = @_; open my $fh, '<', $file or die $!; while( <$fh> ) { lock $sem; cond_wait( $sem ); $Q->enqueue( $_ ); } } my $Q = new Thread::Queue; my $t = async( \&thread, $Q, $ARGV[0] )->detach; my $mw = MainWindow->new; $mw->geometry( "1024x768" ); my $b1; $b1 = $mw->Label->pack( -anchor => 'nw' )->Button( -width => 10, -text => 'start', -command => sub{ if( $sem ) { $b1->configure( -text => 'resume' ); lock $sem; cond_signal( $sem ); $sem = 0; } else{ $b1->configure( -text => 'suspend' ); lock $sem; cond_signal( $sem ); $sem = 1; } } )->pack( -side => 'left' ); my $lb = $mw->Scrolled( 'Listbox', -height => 55, -scrollbars => 'e' )->pack( -anchor => 's', -fill => 'both' )->Subwidget('scrolled'); my $repeat = $mw->repeat( 1 => sub { while( $Q->pending ) { $lb->insert( 'end', $Q->dequeue ); $lb->see( 'end' ); $mw->update; lock $sem; $sem and cond_signal( $sem ); } }); $mw->MainLoop;

Update: Simplified the code a little.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://953775]
help
Chatterbox?
[Lady_Aleena]: This evening, I thought to myself, "I would love to search Netflix for 100 randomfilms from my database to see if they have them." So I went to CPAN to see if there were a modiule which could do such a thing. There is, but GUH! ...
[Lady_Aleena]: ... Does it have to be that hard and complex to use to do a search on Netflix?
Lady_Aleena grumbles.

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2017-01-21 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (180 votes). Check out past polls.