perl multithreading issue for autoincrement
Posted
by
user3446683
on Stack Overflow
See other posts from Stack Overflow
or by user3446683
Published on 2014-08-18T16:23:23Z
Indexed on
2014/08/19
10:20 UTC
Read the original article
Hit count: 192
perl
I'm writing a multi threaded perl script and storing the output in a csv file. I'm trying to insert a field called sl.no. in the csv file for each row entered but as I'm using threads, the sl. no. overlaps in most. Below is an idea of my code snippet.
for ( my $count = 1 ; $count <= 10 ; $count++ ) {
my $t = threads->new( \&sub1, $count );
push( @threads, $t );
}
foreach (@threads) {
my $num = $_->join;
}
sub sub1 {
my $num = shift;
my $start = '...'; #distributing data based on an internal logic
my $end = '...'; #distributing data based on an internal logic
my $next;
for ( my $x = $start ; $x <= $end ; $x++ ) {
my $count = $x + 1;
#part of code from which I get @data which has name and age
my $j = 0;
if ( $x != 0 ) {
$count = $next;
}
foreach (@data) {
#j is required here for some extra code
flock( OUTPUT, LOCK_EX );
print OUTPUT $count . "," . $name . "," . $age . "\n";
flock( OUTPUT, LOCK_UN );
$j++;
$count++;
}
$next = $count;
}
return $num;
}
I need the count to be incremented which is the serial number for the rows that would be inserted in the csv file. Any help would be appreciated.
© Stack Overflow or respective owner