Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Threading in a loop

by andal (Hermit)
on Apr 23, 2013 at 07:14 UTC ( [id://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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1030053]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (5)
As of 2024-03-29 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found