in reply to How do I get a result from a thread?

Yeah, you are making the assumption that a thread sub code block returns automatically, you need to join it, to get the return value.
#!/usr/bin/perl use warnings; use threads; use strict; $|=1; #turn off buffering my $returnn = ""; my $thread = threads->new(sub { print "Run the thread! Variable should be set\n"; sleep(3); $returnn = "bla ble bli"; }); my $result = $thread->join; print $result,"\n";
Notice that the join statement, will block the main program until the thread finishes.

There are other alternatives,i if you want to detect when the thread finishes, using threads::shared. Here I also detach the thread, so you don't need to join it.

#!/usr/bin/perl use warnings; use threads; use threads::shared; use strict; $|=1; #turn off buffering my $returnn : shared; #declare as shared before setting value $returnn = ''; my $thread = threads->new(sub { print "Run the thread! Variable should be set\n"; sleep(3); $returnn = "bla ble bli"; })->detach(); while(1){ if($returnn eq ''){ print "No return yet\n"; sleep 1; }else{ print "return->$returnn\n"; last; } } print "Hit enter to exit\n"; <>;

I'm not really a human, but I play one on earth. flash japh

Replies are listed 'Best First'.
Re^2: How do I get a result from a thread?
by tadeufae (Initiate) on Mar 20, 2006 at 17:09 UTC
    Thanks a lot all of you. Now it works. :DDDDDD =*****