1
votes

I have a problem with pthreads using ANSI C over Linux.

I want to get commands using a thread, so it is waiting for them. But, in a certain case, I need to kill it.

If I use pthread_kill(), it sends a signal and kills the whole process. And, if I am on the right way, pthread_cancel requires the thread to be prepared for it.

Is there any cleaner or more simple way to kill a thread from another one?

Thanks.

1
Possible repeat of stackoverflow.com/questions/2084830/kill-thread-in-pthread, use signal handlers and handle pthread_kill() - vpit3833
Just a side note: You shouldn't say "ANSI C" when you don't mean it. ANSI C is not concerned with threads or other means of executing in parallel. Instead you probably mean a POSIX environment. - Roland Illig
@vpit3833 We thought about that option, may be we should reconsider it... I just wonder if there is more ways. @Roland Illig: You're right. - jesusiniesta

1 Answers

4
votes

You don't say what kind of command/message your thread is waiting for, but if you can send it a "will you please kill yourself" message, and then wait for it to die with pthread_join(...), you'll be much happier.

If your thread is waiting on a file descriptor, you can use poll() or select() and have it wait on two file descriptors. Then your main thread can send it messages on the second one.

If your thread is waiting on GUI events, most toolkits have a way to send your own messages. For instance PostMessage() in Win32, or XSendEvent() in X11.