I put up many threads running. At a later time, I’d like to check if these threads are still alive (i.e., not finished yet and not terminated unexpectedly).
-
What kind of information should I keep track of regarding the threads in the first place. Thread ID, process ID, etc? How should I get these IDs?
-
When I need to check the liveness of these threads, what functions should I use? Will
pthread_killwork here?pthread_killtakes an opaque typepthread_tas parameter, which I believe is typically anunsigned long. Ispthread_tdifferent from a thread ID? I assume a thread ID would pick up an int as its value. In some tutorials on pthread, they assign an integer to a pthread as its ID. Shouldn’t the thread get its ID from the operating system?
A thread’s entire identity resides in
pthread_tInitializing a thread returns its
pthread_ttyped ID to its parentEach thread can get it’s own ID with
pthread_self()You can compare thread IDs using the function:
int pthread_equal (pthread_t, pthread_t)So: Maintain a common data structure where you can store thread status as STARTED, RUNNING, FINISHED using the
pthread_tIDs andpthread_equalcomparison function to differentiate between the threads. The parent sets the value to STARTED when it starts the thread, the thread itself sets its own state to RUNNING, does its work, and sets itself to FINISHED when done. Use a mutex to make sure values are not changed while being read.EDIT:
You can set up a sort of ‘thread destructor’ using
pthread_cleanup_push:http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cleanup_pop.html
i.e. register a routine to be called when the thread exits (either itself, or by cancellation externally). This routine can update the status.