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

Discussion in 'Perl Misc' started by Peng Yu, Jul 28, 2010.

  1. Peng Yu

    Peng Yu Guest

    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;
    Peng Yu, Jul 28, 2010
    #1
    1. Advertising

  2. with <> Peng Yu wrote:
    > 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*

    --
    Torvalds' goal for Linux is very simple: World Domination
    Stallman's goal for GNU is even simpler: Freedom
    Eric Pozharski, Jul 29, 2010
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. nvp
    Replies:
    0
    Views:
    104
  2. nvp
    Replies:
    2
    Views:
    166
    Luc Heinrich
    Dec 31, 2009
  3. Replies:
    0
    Views:
    219
  4. it_says_BALLS_on_your forehead

    Parallel::ForkManager and Net::FTP problem?

    it_says_BALLS_on_your forehead, Oct 7, 2005, in forum: Perl Misc
    Replies:
    3
    Views:
    433
    it_says_BALLS_on_your forehead
    Oct 10, 2005
  5. chaitu
    Replies:
    2
    Views:
    144
    chaitu
    Sep 21, 2006
Loading...

Share This Page