http://www.perlmonks.org?node_id=860090


in reply to How to pause multithreaded application?

So i have one problem: how to pause all running threads (and continue them after some user actions)?

Add a shared variable initialised to false, and have the main loop within your thread code check it each time around.

When the user clicks the pause button, the action sets the shared var to true.

When the thread-loops next check the shared var, and it is true; they just sleep a little and loop until it becomes false again.

To resume, the button sets the shared var false again, and off they all go.

my $paused :shared = 0; sub thread { while( my $domain = $queue->dequeue ) { sleep 1 while $paused; ## the rest of the thread code. } } ... $pauseButton->onclick( sub { if( $paused ) { $paused = 0; $self->settext( "Pause" ); } else { $paused = 1; $self->settext( "resume" ); } } }; ...

Simple and reliable.

Beware the "threads signals", they are essentially useless.

As they do not interupt running code as real signals do, you therefore have to arrange to poll them, in order to notice that you've been signalled. At which point, all the ridiculous and buggy code that underlies them becomes completely redundant because you're better off just polling a shared var as above.


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.