in reply to Re^5: Execute a sub in the background
in thread Execute a sub in the background

Well here is the situatian. As i mentioned the sub in the thread keeps going and my main program also keeps going.

I want in the main process when i hit a button to stop the cycle in the thread. Is there such way. I mean maybe to use a flag in the sub(tried this it didn't reflect anything). So is there a way to end the cycle in the sub

This is what i mean by killing it i want to stop this sub or simply execute return in it when there i a button pressed in the main process

Replies are listed 'Best First'.
Re^7: Execute a sub in the background
by chessgui (Scribe) on Feb 01, 2012 at 16:08 UTC
    I did some research on this because I run chess engines which may get out of hand. I was wondering if I can kill a handler thread when the engine freezes. It is far from being natural and easy. From what I've read I gathered that 'killing' threads from the outside is a thing you should avoid. I personally use the Tk event loop for event driven programming. I only use threads for shepherding processes which are started once and run all the way long paralelly with the MainLoop. Normally there is no need to 'kill' such a thread.

      Ok i understand. So is there a way to share a variable or maybe to sent a reference to the sub.

      What i want is to have a flag in the main process when its value is one the cycle in the thread to end. How can i do this. I checked the threads::schared but honestly i wasn't able to do anything. So if you could help me whit some example code it would be great

        Experts will tell you to use Thread::Queue. I have not much experience with queues. However this is what you can achieve with shared variables:
        use threads; use threads::shared; my ($global):shared; my $handler=threads->create(\&handler)->detach; do { print "Enter a value for shared global variable ( x = exit ): ";ch +omp($global=<>); sleep(3); } while($global ne 'x'); sub handler { my $global_old=$global; while(1) { if($global ne $global_old) { print "User changed the global variable to '$global'.\n"; $global_old=$global; } sleep(1); } }