Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to interrupt a thread which is waiting on recv function? [duplicate]

Tags:

c++

sockets

I have a socket listener which hangs on recv function:

size_t recvLen = recv(sock, buf, 512, 0);

I would like to terminate this thread with interrupting it. MSDN says:

When issuing a blocking Winsock call such as recv, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread.

How can I do that?

like image 736
MCA Avatar asked Mar 02 '11 13:03

MCA


1 Answers

You can interrupt it by queuing an APC to it via QueueUserAPC. However, it's most likely unsafe to terminate the thread in the APC. Queuing an APC doesn't end the recv, it just interrupts it; once the APC returns, it will go back to waiting on recv again.

If you want to stop the recv completely, you should be using select with a timeout to wait until data is available. You can then check whether you should keep waiting for data or continue at each timeout.

like image 135
Collin Dauphinee Avatar answered Sep 19 '22 22:09

Collin Dauphinee