in reply to Is returning a list broken when using threads?

I haven't used threads before, but I found the following in perldoc threads for Perl 5.8.3 (typo corrected):

The context (scalar or list) of the thread creation is also the context for join(). This means that if you intend to return an array from a thread, you must use "my ($thread) = threads->new(...)", and that if you intend to return a scalar, you must use "my $thread = ...".

Now that I think about it, it kinda has to be that way. It can't use the context for the join call, because that's too late. The called routine has to be able to invoke wantarray from the moment it's called and get the right result.

  • Comment on Re: Is returning a list broken when using threads?

Replies are listed 'Best First'.
Re^2: Is returning a list broken when using threads?
by beable (Friar) on Jul 25, 2004 at 02:55 UTC
    Riiiiight, so this example from perlthrtut is rather misleading then:
    Waiting For A Thread To Exit Since threads are also subroutines, they can return values. To wait for a thread to exit and extract any values it might return, you can use the join() method: use threads; $thr = threads->new(\&sub1); @ReturnData = $thr->join; print "Thread returned @ReturnData"; sub sub1 { return "Fifty-six", "foo", 2; } In the example above, the join() method returns as soon as the thread ends. In addition to waiting for a thread to finish and gathering up any values that the thread might have returned, join() also performs any OS cleanup necessary for the thread. That cleanup might be impor- tant, especially for long-running programs that spawn lots of threads. If you don't want the return values and don't want to wait for the thread to finish, you should call the detach() method instead, as described next.
    Thanks!

      I think the problem with perlthrtut and some other bits of the documentation (what there is of it), was mostly written for 5005threads and hasn't really caught up with ithreads yet.

      That said. I'm not sure how the snippet you quote would have worked then either.


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon
      Patches are welcome. (Appreciated even.)
        Just a wild idea: could the thread routine not provide the return result for all possible contexts (scalar, array, boolean, ...) and have the join routine pick the one it needs as per its own context?

        CountZero

        "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law