How to stop a thread by sending a signal

248 views Asked by At

Suppose a thread is running some code:

// thread
while (_running)                 // (1)
{
   rv = read(...);               // (2)
   // do something with data
}

We can add a signal handler to stop the thread:

// signal handler
_running = false;

And use pthread_kill to execute this handler on the thread. This would unblock the read at (2).

This approach has a race-condition: If the signal handler executes between (1) and (2), the thread will not be stopped.

How can this race-condition be avoided?

0

There are 0 answers