views:

85

answers:

2

I have a project where Thread A calls Accept(...) on some socket, then it passes it to another thread, which does receive on the socket and then closes the socket.

The object on which accept was called is never closed in Thread A. Is that safe?

What happens to that object in Thread A?

+4  A: 

A socket is not an object - it's just a number (or conceivably a pointer). If you pass an integer from one thread to another, there are no issues - the same with sockets. This assumes you are asking about OS level sockets, and not some socket class that you or a framework you are using have implemented, and that you only access the socket from one of the threads, which seems to be the case.

anon
A: 

Yes it will close. But this will not assure that the unused socket is immediately available for garbage collection (reference in ThreadA)

Sockets & Threads, a few golden rule...

  • Socket objects are not tread safe, make sure that you're using some sort of lock/mutex to access this resource (think synchronization)
  • Socket access (like any other I/O) is a blocking operation, this can create a LOT of contention (and waste a lot of CPU cycles) in case of multi-threaded access
  • ALWAYS explicitly close sockets (server or client), just to be double sure & not surprise yourself l8r
  • if you're continuously going to read data from a socket & other threads are going to consume this data, USE a thread safe data structure (a concurrent queue) for other threads to consume from. so one thread just reads data from the socket & makes it available on the queue, from where the other threads can work on the data
ksm