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?