Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Threading in a loop

by andal (Hermit)
on Apr 23, 2013 at 07:14 UTC ( #1030053=note: print w/replies, xml ) Need Help??

in reply to Threading in a loop

As already said, your thread prints the value only once, and that can be any value, depending on when the thread got chance to work. If you want your thread to print value every time when it changes, then you have to establish some coordination between your main thread and started thread. In this particular case you may use 2 Thread::Queue objects. Your main thread will push something in the first queue when it incremented the value and wait on the second queue for the moment when the started thread has printed the value. The started thread will wait on the first queue for the moment when the variable was incremented, print the value and then push something into second queue to indicate that printing is finished.

As you may already see, threads don't make any sense for such simple situation. They just make things complex. In general, try to avoid using threads. They make sense only if they don't modify the same data, at least they do it infrequently. In the best case, a thread would just produce some result and nothing else. Any time there's some shared data, you have a headache of synchronizing access to this data, you have to use locks, semaphores, queues, whatever. And you have to worry about dead-locking and race conditions.

Don't take me wrong. Threads do have benefits, but they come at cost, and in certain situations the cost becomes too high :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1030053]
[Corion]: karlgoethebier: Haha ;) I'm still looking for something like Sonos, but with open software that doesn't only stream Spotify and nothing else
[Corion]: But until then, I just make-do with my stereo speakers. I think I'm approaching the age where my ears won't notice the difference anymore :)

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2018-04-20 07:02 GMT
Find Nodes?
    Voting Booth?