Socket in multiple threads

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

The object on which accept was called never closes in Thread A. Is it safe?

What happens to this object in Thread A?

+3
source share
2 answers

A socket is not an object - it is just a number (or, presumably, a pointer). If you pass an integer from one stream to another, then there is no problem - the same with sockets. This assumes that you are asking about OS-level sockets, not some class of sockets that you or the framework you use have implemented, and that you only get access to the socket from one of the threads, which looks like this.

+4
source

Yes, it will close. But this does not guarantee that an unused socket is immediately available for garbage collection (link in ThreadA)

Sockets and flows, a few golden rules ...

  • Socket objects are not protected from the tread, make sure you use some kind of lock / mutex to access this resource (think about synchronization)
  • ( -) - , ( ) .
  • ( ), l8r
  • , , USE ( ) , . , .
0

Source: https://habr.com/ru/post/1747863/


All Articles