1

There is a piece of code running in my stack which waits on pthread_cond_wait. A signal is send to the same process but there is no "pthread_cond_signal" code in the signal handler to notify the pthread_cond_wait but still pthread_cond_wait is released. There are other threads who usually does "pthread_cond_wait" to release the wait but none of them are active at this point.

aTJ
  • 3,823
  • 3
  • 21
  • 25

2 Answers2

2

pthread_cond_wait() can wake up at any time, even if it has not been signalled.

This is called a "spurious wakeup", and correct code must handle this - in most cases, the correct way to call pthread_cond_wait() is within a loop structured like:

while (!condition_waiting_for)
    pthread_cond_wait(&cond, &mutex);

Where condition_waiting_for is the condition over your program's shared state that your thread is waiting to become true (for example, "job queue is not empty").

When you structure your pthread_cond_wait() call like this, spurious wakeups - including wakeups that might be caused by signals - do not affect the correctness of your program.

caf
  • 233,326
  • 40
  • 323
  • 462
0

The pthread_cond_wait can be signaled by pthread_cond_signal or pthread_cond_broadcast.

Also, a pthread can be cancelled with pthread_cancel, which sends a cancellation request to the thread. After sending the request to cancel the thread you should check the return code to confirm that the thread was actually cancelled.

There's a good thread discussing how to kill a pthread.

RonTLV
  • 2,376
  • 2
  • 24
  • 38
  • 1
    My question is different. I'm asking whether it is safe from other signals like user-defined ones. Because I know for a fact sem_wait is not completely signal safe, checkout https://linux.die.net/man/3/sem_wait --> A signal handler always interrupts a blocked call to one of these functions, regardless of the use of the sigaction(2) SA_RESTART flag – aTJ Aug 29 '17 at 05:33