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.

1    void Disconnect()
2   {
3       if (isConnected)
4       {
5           if (closesocket(sockClient) != SOCKET_ERROR)
6           {
7               isConnected = false;
8           }
9       }
10   }

How should I 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.

Need Your Help

Inserting greater/less than or equal symbol into SQL Server database

sql-server unicode nvarchar

I am trying to insert ≤ and ≥ into a symbol table where the column is of type nvarchar.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.