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 reply to Re: Threading in a loop by andal
in thread Threading in a loop by jerre_111

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.