简体   繁体   中英

Does Perl's thread join method wait for the first thread to finish if I launch more than one thread?

     foreach $name (@project_list)
     {
               # a thread is created for each project
               my $t = threads->new(\&do_work, $name);
               push(@threads, $t);
     } 

    foreach (@threads) {
     my $thrd = $_->join;
     print "Thread $thrd done\n";
    }

    sub do_work {
     # execute some commands here...
    }

The project_list is a list of 40 items. When I spawn a thread for each item, will the join method wait for the first thread to finish and then move over to the next one and so on?

If that is the case, then is it possible to avoid it? I mean some threads will finish faster then others so why wait?

Please let me know if more information is required. Thank you.

$_->join waits for the thread designated by $_ to finish. Since you're pushing them in order, and foreach traverses the list in order, yes, you'll wait first for the first thread.

But that doesn't matter since you're waiting for all threads to finish. It doesn't matter if you wait for the fastest finishers or the slowest ones first - you'll be waiting for everyone anyway.

Why wait? It depends on the scope of the post-processing step.

If the post-processing step needs all threads to finish before beginning work, then the wait for individual threads is unavoidable.

If the post-processing step is specific to the results of each thread, it should be possible to make the post-processing part of the thread itself.

In both cases, $_->join foreach @threads; is the way to go.


If there is no need to wait for the threads to finish, use the detach command instead of join . However, any results that the threads may return will be discarded.

The main thread has to live for the duration of all threads so you need to know when they are all done. The can be done queues or semaphores. Semaphores are the simplest:

use Thread::Semaphore;

my $S = Thread::Semaphore->new();


foreach $name (@project_list)
{
    # a thread is created for each project
    my $t = threads->new(\&do_work, $name);
    $S->down_force();                        # take one for each thread
} 

$S->down();                # this blocks until worker threads release one each
print "Thread $thrd done\n";


sub do_work {
    # execute some commands here...
    $S->up();             # here the worker gives one back when done.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM