Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to do something when a Perl thread finishes its work?

Let's say I have 10 threads running simultaneously. Is there any way of calling some method when a thread finishes? I was thinking of something like:

$thread->onFinish(sub { print "I'm done"; });
like image 605
Geo Avatar asked Mar 06 '10 14:03

Geo


People also ask

How threads are managed in Perl?

Currently Perl assigns a unique TID to every thread ever created in your program, assigning the first thread to be created a TID of 1, and increasing the TID by 1 for each new thread that's created. When used as a class method, threads->tid() can be used by a thread to get its own TID.

Does Perl have multithreading?

Perl can do asynchronous programming with modules like IO::Async or Coro, but it's single threaded. You can compile Perl with threads, which provide multi-threaded computing.

When should you not use threads?

If the sum of your threads is <100% of one core, then there is no reason whatsoever for you to use threads. If your program is not CPU bound, then you would be infinitely wiser to use an event loop1 or coroutines2. If you are not CPU bound, then the entire value proposition of threads does not apply to you.


1 Answers

The question you ask in the title and the one you ask in the body are different.

The standard way for a different thread to find out if a thread is still running is to either wait for it or poll it using is_running and/or is_joinable depending on your particular needs.

If all you want is for the i'm done to be printed, well, make sure that is the last statement executed in the thread body, and it will be printed.

threads->create(sub {
    # call the actual routine that does the work
    print "i'm finished\n";
});
like image 61
Sinan Ünür Avatar answered Sep 21 '22 23:09

Sinan Ünür