There are many different ways you can handle this.
You can abort a blocked accept()
by simply closing the listening socket.
Or, you can use select()
with a short timeout to detect when a new client is waiting before then calling accept()
. You can check your exit condition in between calls to select()
. Just be aware that there is a small race condition where a client may disconnect between the time select()
and accect()
are called, so accept()
may still block, if there are no more clients waiting.
Or, you can get rid of your threads and just use non-blocking sockets in a single thread, checking your exit condition periodically in between socket operations.
Or, you can use asynchronous sockets, using WSACreateEvent()
, WSAEventSelect()
, and WSAWaitForMultipleEvents()
to detect socket activity. Then you can create an addition event to wait on for when the exit condition happens.
Or, you can use an I/O Completion Port to handle socket activity, and then you can post a custom exit packet into the IOCP queue using PostQueuedCompletionStatus()
to "wake up" any waiting threads.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…