2

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?

garima721
  • 323
  • 3
  • 14
  • 1
    possible duplicate of [How to signal select() to return immediately?](http://stackoverflow.com/questions/384391/how-to-signal-select-to-return-immediately) – Dan Cornilescu Jun 09 '15 at 14:01
  • Yes thanku, one way is to add a pipe in the list of sockets polled by select and another is to kill it as mentioned by David. – garima721 Jun 11 '15 at 03:14

2 Answers2

1

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.

David Harrison
  • 256
  • 1
  • 9
  • pthread_kill( T1, SIGUSR1 ); This will send the signal SIGUSR1 to pthread T1. Assuming you are using pthreads, of course. – David Harrison Jun 10 '15 at 12:07
  • By the way, I used boost::threads under Linux in my approach given above. I just used the lower-level pthread_kill() function, passing T1.native_handle() as the first parameter. – David Harrison Jun 10 '15 at 14:35
  • Thanku so much, I also use boost thread and couldn't find a way to kill boost thread. This just worked. – garima721 Jun 11 '15 at 03:13
0

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);
Gil Hamilton
  • 11,973
  • 28
  • 51
  • I am using boost thread, which doesn't provide any api to kill a thread. – garima721 Jun 10 '15 at 03:14
  • This is not correct answer, in case you do some memory allocation in T1 and you call pthread_cancel(), who will clean up all memory allocated by T1? If you still want to use this approach then you should attach clean up routine. Check documentation for pthread_cleanup_push(), pthread_cleanup_pop(). – sfelber Mar 09 '17 at 13:08