Bijan
Bijan

Reputation: 8586

Perl Thread To Increment Variable

I have the following Perl code::

#!/usr/bin/perl

use threads;
use Thread::Queue;
use DateTime;

$| = 1; my $numthreads  = 20;

$min = 1;
$max = 100;

my $fetch_q   = Thread::Queue->new();
our $total = 0;
sub fetch {
    while ( my $target = $fetch_q->dequeue() ) {
            print $total++ . " ";
    }
}

my @workers = map { threads->create( \&fetch ) } 1 .. $numthreads;

$fetch_q->enqueue( $min .. $max );
$fetch_q->end();

foreach my $thr (@workers) {$thr->join();}

The code creates 20 threads and then increments a variable $total.

The current output is something like:

0 0 0 0 0 1 0 0 1 1 2 0 0 1 0 2 0 3 0 1 0 2 1 0 2 1 0 0 3 0

But the desired output is:

1 2 3 4 5 6 7 8 9 10 .... 30

Is there a way to have Perl increment the variable? The order does not matter (i.e. its fine if it is 1 2 4 5 3).

Upvotes: 1

Views: 210

Answers (1)

ikegami
ikegami

Reputation: 385556

use threads::shared;

my $total :shared = 0;

lock $total;
print ++$total . " ";

Upvotes: 5

Related Questions