I have a thread that `read()`s from a socket, and I want to be able to stop the thread asynchronously. The thread pseudocode looks like:

```
int needs_quit = 0;

void *thread_read(void *arg)
{
    while(1)
    {
        if(needs_quit)
        {
            close(sock_fd);
            return NULL;
        }
        int ret = read(sock_fd ...);
        if(ret == EINTR) //we received an interrupt signal to stop
        {
            close(sock_fd);
            return NULL;
        } 
        //do stuff with read data
    }
}

```

The signal handler simply sets `needs_quit` to 1. Most of the time, this code will work. But, if a signal arrives after `if(needs_quit)` and before `read(sock_fd ...)`, then `read()` will not be interrupted, and the thread will never stop. What is the best solution for this problem?

I should point out that I managed to write a working solution with `pthread_cancel`, but as it turns out, I'm not allowed to use that due to compatibility issues.

Thanks in advance for any feedback.