Pthread_kill segmentation error

GDB tells me that pthread_kill is causing a segmentation error in my program. I mainly use pthread_kill to check if a thread is alive or not its id.

I searched the Internet and found that it may be that pthread_kill causes a segmentation error when the TID is invalid. Yes, I tested my program using the "invalid" (invented by me) TIDs of type int . Could this be the real reason?

+8
c segmentation-fault linux pthreads posix
source share
2 answers

pthread_t not a thread identifier or a numerical index. This is an opaque type. Creating values ​​may cause a crash.

On Linux NPTL pthread_t is used as a pointer:

 int __pthread_kill (threadid, signo) pthread_t threadid; int signo; { struct pthread *pd = (struct pthread *) threadid; 

It should be clear enough where everything goes wrong :) Note that this pointerness is also an implementation detail - the older Linuxthreads implementation used numeric indexes in the table, and there you could really make up the TID and not expect things to crash.

You need to track the life of life and death yourself. A pthread_t is valid until you call pthread_join on it successfully. If you want to check if a valid pthread_t alive, type pthread_tryjoin_np ; if it returns EBUSY , the stream is alive. If the function succeeds, pthread_t no longer valid; you should not reuse it at this moment - so you should make a note somewhere that this thread is already dead and there is no need to check it anymore!

You could, of course, implement your own tracking system - create a table somewhere out of vitality, a system for transmitting TIDs and transfer them to newly created streams. Each thread should be dead before exiting (possibly using pthread_cleanup_push so that you handle thread cancellation and pthread_exit ) and disconnect the thread so you don't need to join it (using pthread_detach ). You now have clear control over flow-death reports.

+14
source share

To get around this limitation in my code, I set the TID to zero when the code doesn't work

 memset(&thread, '\0', sizeof(pthread_t)); 

... and check it for null before calling pthread_kill

 //this code will run if thread is not valid if (!thread || ESRCH == pthread_kill(thread, 0)) { //do stuff and create the thread } 
+1
source share

All Articles