Search code examples
cmultithreadingwaitpid

How to check any thread is working currently


I know there is one for multi processes

 waitpid(-1,WNOHANG,NULL)

that is non-blocking function call to check if there is any child process currently working on

But is there any similar lib function to check for multithread?

All i want to do is check if there is any thread currently on, if not reset some global values.


Solution

  • that is non-blocking function call to check if there is any child process currently working on

    Wrong. That is a call to check if there is any child process not yet terminated. And it not only checks but also reaps a terminated child, if any. Children might be otherwise in any possible state, like hanging in a deadlock (what on my book is far from being working).

    All i want to do is check if there is any thread currently on, if not reset some global values.

    Probably you should post here as a question why you want to do it. It sounds that you do something terribly wrong.

    If you do not do already pthread_join() for your threads, that means that your threads already do pthread_detach(). If you had no problems adding to your threads pthread_detach() I think there would be no problem to add some extra code to threads to identify that they have (almost) terminated (e.g. sem_post()) so that main() can notice that a thread had terminated (e.g. by calling sem_trylock()).

    If portability isn't a requirement, then one can also try query OS number of threads of the process periodically.

    Though it is still IMO wrong to have in a program some threads, with undefined life cycle, without any proper sync with main thread.