Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking pthread_join

Tags:

I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.

Is there a way of doing a non-blocking pthread_join? Some sort of timed join would be good too.

something like this:

 foreach thread do   nb_pthread_join();     if still running       pthread_cancel(); 

I can think more cases where a a non-bloking join would be useful.

As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.

like image 367
Figo Avatar asked Sep 16 '08 15:09

Figo


People also ask

Does pthread_join block?

The pthread_join subroutine blocks the calling thread until the thread thread terminates. The target thread's termination status is returned in the status parameter. If the target thread is already terminated, but not yet detached, the subroutine returns immediately.

What happens if you don't use pthread_join?

If you want to be sure that your thread have actually finished, you want to call pthread_join . If you don't, then terminating your program will terminate all the unfinished thread abruptly.

Can any thread call pthread_join?

Yes, this is possible. Indeed, this possibility is one of the main reasons why pthread_detach() exists.

What does the pthread_join function do?

The pthread_join() function waits for a thread to terminate, detaches the thread, then returns the threads exit status. If the status parameter is NULL, the threads exit status is not returned.


1 Answers

If you are running your application on Linux, you may be interested to know that:

int pthread_tryjoin_np(pthread_t thread, void **retval);  int pthread_timedjoin_np(pthread_t thread, void **retval,                                 const struct timespec *abstime); 

Be careful, as the suffix suggests it, "np" means "non-portable". They are not POSIX standard, gnu extensions, useful though.

link to man page

like image 54
yves Baumes Avatar answered Oct 10 '22 17:10

yves Baumes