How can I exit from a select system call at any random time?

2.2k Views Asked by At

Suppose there are 2 threads, T1 and T2.

T1 is selecting on a set of sockets and performs corresponding read/write operations. Now if thread T2 wants to close thread T1 (i.e. join it), then how can I do so, if T1 is blocked on select system call? How can I interrupt select call?

2

There are 2 best solutions below

2
On

Since you just want to kill the thread, this should work.

In T1:

pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
select(...);

In T2:

pthread_cancel(t1);
pthread_join(t1, &retval);
3
On

If you want to be able to clean up after yourself on thread T1, a better answer would be to send yourself a signal from T2 (I've used the USR1 signal before), which would cause the select() call in T1 to return with a value of EINTR.

You could then check for EINTR and know that you needed some cleanup done and do it. In my case, I had a separate thread that was in an infinitely-blocked select() waiting for reading, in a while loop with an exit flag.

while ( !exit_flag )
{
    ...
    int select_retval = select( ... );

    switch ( select_retval )
    {
        case EINTR:
            /* clean up */
            break;
        default:
            break;
    }
}

I would set the exit flag from T2 and then send the signal to T1. T1 would then clean up and then get out of the loop. In my case, the loop was the function running in T1, thus T1 would end.