How to handle same socket in different threads?


I am trying to handle socket in different threads creating runtime failure. See following code.

void MySocket::Lock() { m_LockCount++; if( m_LockCount ) { CSocket::Create( 8080 ); } } void MySocket::Unlock() { m_LockCount--; if( !m_LockCount ) { CSocket::Close(); } }

I am calling Lock() from one thread and Unlock() from other. When it executes CSocket::Close() it gives an exception.

I googled for this bug and got some reasons. This happens because; a CSocket object should be used only in the context of a single thread because the SOCKET handle encapsulated by a CAsyncSocket object is stored in a per-thread handle map. They are also suggesting a solution by sharing SOCKET handles between threads (<a href="http://support.microsoft.com/kb/175668" rel="nofollow">http://support.microsoft.com/kb/175668</a>). But this is not possible in my case since I am excepting some notification callback which will not work with above solution. Can anybody suggest a mechanism to share CSocket among threads without effecting notification callbacks?


If, as you say, "a CSocket object should be used only in the context of a single thread," then there is no "mechanism to share CSocket among threads".

In other words, one of the threads needs to own the CSocket, and the others can't mess with it.

In such cases, the solution is to use an inter-thread messaging system. That way, one of the other threads can send a message to the owner saying, "Hey, buddy, close your socket!"

The details of how you would do that messaging depend entirely on the context of your program.


You coould just use the socket directly and stop using the, obviously, flawed MFC implementation ...


I would advise you to use some higher-level (and less buggy) socket API like <a href="http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio.html" rel="nofollow">Boost.Asio</a>. Note that it does not make sockets thread-safe anyway (see <a href="http://www.nabble.com/-ASIO--Thread-safety-of-socket.write_some---socket.read_some-td20222810.html" rel="nofollow">there</a>). You have to use some lock/unlock facility.

I am not sure i understand your question about sharing sockets among threads without using notification callbacks. Between threads T1 and T2, supposing T1 manages a socket, there are only two ways for T2 to become aware of a socket event. Either some notification launched by T1 or a question asked by T2 to T1, either on a regular basis or in a blocking call.


  • Bluetooth LE TX Power reading
  • How to terminate a process
  • Windows Azure VM availability/Failover steps
  • How to get an estimated amount of talktime,music/video playback time, idletime that could be possibl
  • matplotlib example code not working on python virtual environment
  • Accesing properties in a UserControl from the MainWindow (WPF/MVVM)
  • Convert gwt project into maven gwt project
  • How to send an std::vector of unsigned char over an UDP socket using boost asio?
  • iOS - How to access the device's file library?
  • MVC - Dynamically loading Partial Views
  • How to read data from socket connection - android
  • Cannot send user message with Spring Websocket
  • Keep pika BlockingConnection alive without disabling heartbeat
  • UIImagePickerControllerDelegate Methods Not Called When Delegate Not UIViewController
  • Jquery resizable reposition handle after scroll
  • Is there a way to link a linux's thread TID and a pthread_t “thread ID”
  • Should I be afraid to use UDP to make a client/server broadcast talk?
  • 'doc_del_count' bigger than 'doc_count' on CouchDB
  • Error in making a socket connection
  • Find group of records that match multiple values
  • Hardware Accelerated Image Scaling in windows using C++
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Excel - Autoshape get it's name from cell (value)
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • script to move all files from one location to another location
  • Check if a string to interpolate provides expected placeholders
  • Can I make an Android app that runs a web view in Chrome 39?
  • Redux, normalised entities and lodash merge
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • How do you troubleshoot character encoding problems?
  • Do create extension work in single-user mode in postgres?
  • RestKit - RKRequestDelegate does not exist
  • Traverse Array and Display in markup
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • How to include full .NET prerequisite for Wix Burn installer
  • Turn off referential integrity in Derby? is it possible?
  • JaxB to read class hierarchy
  • Running Map reduces the dimensions of the matrices
  • Android Heatmap on canvas or ImageView