Geo
Geo

Reputation: 96957

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"; });

Upvotes: 5

Views: 133

Answers (2)

Sinan Ünür
Sinan Ünür

Reputation: 118166

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";
});

Upvotes: 5

Tamás Szelei
Tamás Szelei

Reputation: 23971

I'm really in the dark here, so it's just a general suggestion: you could implement a callback mechanism. If nothing else, you could pass an object with the onFinish method when the thread starts. And call that function from the thread when it finishes it's work (according to it's internal state).

Upvotes: 1

Related Questions