perl multithreading issue for autoincrement -


i'm writing multi threaded perl script , storing output in csv file. i'm trying insert field called sl.no. in csv file each row entered i'm using threads, sl. no. overlaps in most. below idea of code snippet.

for ( $count = 1 ; $count <= 10 ; $count++ ) {     $t = threads->new( \&sub1, $count );     push( @threads, $t ); }  foreach (@threads) {     $num = $_->join; }  sub sub1 {     $num = shift;      $start = '...';    #distributing data based on internal logic     $end   = '...';    #distributing data based on internal logic     $next;      ( $x = $start ; $x <= $end ; $x++ ) {         $count = $x + 1;          #part of code @data has name , age          $j = 0;         if ( $x != 0 ) {             $count = $next;         }         foreach (@data) {             #j required here code             flock( output, lock_ex );             print output $count . "," . $name . "," . $age . "\n";             flock( output, lock_un );             $j++;             $count++;          }         $next = $count;     }      return $num; } 

i need count incremented serial number rows inserted in csv file. appreciated.

you're providing mutual exclusion using flock, might take advantage of if that's place $count used.

my $counter :shared;  # once threads (@data) {     ...     flock( output, lock_ex );     print output ++$count . "," . $name . "," . $age . "\n";     flock( output, lock_un );  } 

or can switch using perl locks.

my $counter :shared;  # once threads (@data) {     ...     {        lock $counter;        print output ++$count . "," . $name . "," . $age . "\n";     }  } 

in both cases, lines in output file numerical order.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -