Multithreading - Disconnect TCP Connection
I create a thread to receive on a blocking socket, It waits until the packets arrive. However when I try to disconnect from primary thread, race conditions occur between the threads which lead to errors.
Here the switch occurs at line 5 between threads without actually finishing the disconnect call.
void Disconnect() {
if(isConnected) {
if (closesocket(sockClient) != SOCKET_ERROR) {
isConnected = false;
}
}
}
How should I开发者_C百科 avoid switches and gracefully let it finish the disconnect call?
Here are two possible solutions.
You can isolate ALL socket access in the socket (non-primary) thread, and instead of disconnecting the socket from the primary thread, have that thread signal the non-primary thread that disconnect (or some other action) is needed. This would require your secondary thread to wait on two objects - the socket, and a signaller (Win32 Event, say) that indicates a disconnect is required.
If on the other hand you want to allow primary thread to disconnect (as you do now), you need to check all your code that uses the socket, and make it thread-safe using lock guards to ensure concurrent access to the socket and associated state data is prevented. Boost.Thread has suitable locks that you can use here, otherwise you can implement your own as a wrapper on something like Win32 CriticalSection.
The second would be my preferred solution - the fact that you are asking this question means you need to go back and think about thread safety in your design anyway. Even if you go with the first idea above, you still likely need to maintain state to avoid multiple disconnect signals being sent from the primary thread, and that would have to be lock guarded. Also if you wish the non-primary thread to handle incoming events other than 'disconnect', there would be associated state that would have to be managed between the threads.
I think the path of least resistance from where you are now is to add locking to your existing code. Make sure you scope your locks as narrowly as possible - do not set up a lock that you hold across any socket call that can blocks or take a long time, for example.
精彩评论