good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Re: Threading in a loopby andal (Hermit) |
on Apr 23, 2013 at 07:14 UTC ( [id://1030053]=note: print w/replies, xml ) | Need Help?? |
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 :)
In Section
Seekers of Perl Wisdom
|
|