in reply to wait for threads to end in parallel

What about:

You'll also note that there's a semicolon after the closing brace. That's because async() treats the following block as an anonymous subroutine, so the semicolon is necessary.

and:

threads->list() returns a list of thread objects, one for each thread that's currently running and not detached. Handy for a number of things, including cleaning up at the end of your program (from the main Perl thread, of course):
# Loop through all the threads foreach my $thr (threads->list()) { $thr->join(); }

Is there any difference between threads->create() and async {...}?

Replies are listed 'Best First'.
Re^2: wait for threads to end in parallel
by ikegami (Patriarch) on Mar 16, 2010 at 16:14 UTC

    Syntax. async is shorter, but can only pass args via capture. Then again, passing args via create is known to be problematic.

    Without args:

    async(\&process); async { process(); }; thread->create(\&process);

    With args:

    async { process($arg); }; thread->create(\&process, $arg); # Safe??
      Syntax. async is shorter, but can only pass args via capture.

      Not so. async is identical to threads->create(), except that it is invoked as a function rather than a class method:

      # 'async' is a function alias for the 'threads->create()' method sub async (&;@) { unshift(@_, 'threads'); # Use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8. +2) goto &create; }

      So async \&sub, $arg, 1, 'fred'; or even async{ ... } $arg, 1, 'fred';

      are identical in effect to threads->create( \&sub, $arg, 1, 'fred' );


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Ah yes, I forgot about that. Revised answer:


        Syntax. async is shorter, and it simply pass args via capture. That's good, because passing args to a thread as arguments is known to be problematic*.

        Without args:

        async(\&process); async { process(); }; thread->create(\&process);

        With args:

        async(\&process, $arg); # Safe?? thread->create(\&process, $arg); # Safe?? async { process($arg); }; thread->create(sub { process($arg) });

        * — The stack isn't ref-counted, and this causes issues when thread creation attempts to clone the variables. I can't remember the exact scenario, but I can look it up if you want more info.