Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re^3: Threading in a loop

by hdb (Monsignor)
on Apr 22, 2013 at 14:11 UTC ( #1029884=note: print w/replies, xml ) Need Help??

in reply to Re^2: Threading in a loop
in thread Threading in a loop

Your program finishes too fast. Try this:

use threads; use threads::shared; my $test :shared; $test = 0; testing_thread(); sub testing_thread { my $thr1 = threads->create(\&progress_count, $test); while ($test <= 1000000) { $test += 1; } $thr1->join(); } sub progress_count { while( $test < 1000000 ) { print $test, " \n"; } }

Replies are listed 'Best First'.
Re^4: Threading in a loop
by jerre_111 (Sexton) on Apr 22, 2013 at 14:26 UTC

    I'm sorry to say, but your code is not quite right.

    When you do it like that, the printing and counting of the variable won't run parallel. Resulting in seeing only fragments of the counting

    But thanks for the effort!

      Is that not expected? When you asynchronously increment the variable and print the variable it will not be in line. There is nothing in the code to synchronize the two.

        When you execute the following code you get a synchronised counting/printing action

        use threads; use threads::shared; my $test :shared; $test = 0; testing_thread(); sub testing_thread { while ($test <= 100) { my $thr1 = threads->create(\&progress_count, $test); $test += 1; $thr1->join(); } } sub progress_count { print $test, " \n"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1029884]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2018-06-24 12:13 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.