How to synchronize I/O (Parallel::ForkManager)

P

Peng Yu

I have the following code. The there is a chance that the two print
line (with '#') may not function print consecutively. Is there a way
to lock so that I can guarantee they write consecutively?

$ cat main.pl
#!/usr/bin/env perl

use strict;
use warnings;

use Parallel::ForkManager;

open OUT, ">main.txt";

my $pm = new Parallel::ForkManager(5);

foreach my $n (1..10) {
my $pid = $pm->start and next;
print $n, "\n";
sleep rand(1);
print OUT $n;#
print OUT $n;#
$pm->finish;
}

$pm->wait_all_children;
 
E

Eric Pozharski

with said:
I have the following code. The there is a chance that the two print
line (with '#') may not function print consecutively. Is there a way
to lock so that I can guarantee they write consecutively? *SKIP*
sleep rand(1);

Please, read carefully the very last paragraph of 'perldoc -f sleep'

% perl -wle 'print "$_ -> ", sleep $_ foreach map rand 1, 0 .. 10'
0.040502967153774 -> 0
0.135818231941329 -> 0
0.57742617841917 -> 0
0.999873014489772 -> 0
0.560751288326248 -> 0
0.480306753175668 -> 0
0.0107077151972952 -> 0
0.870398831594763 -> 0
0.131003141627307 -> 0
0.957688366820321 -> 0
0.803041790395394 -> 0

(That's just "my 0.02$"; others showed you light already)

*CUT*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top