17

I'm using both Linux and Win32 socket APIs. In my program, multiple threads share a socket handle. In particular, multiple threads call send with the shared socket handle (i.e., the same port). In this case, do I have to put a lock for thread safety? I was unable to find the answer. I may do a test, but want to hear your experiences.

EDIT: I know that such sending data via socket isn't atomic operation at all. Definitely we have to use a mutex for thread safety. However, I was wondering whether the system API could have their own internal lock. If so, we can omit putting our own lock.

This question may be applicable to fprintf function as well. I'm wondering such system APIs would have their own locks. In my experience, calling fprintf from multiple threads didn't kill my program although there was races on a file or stdout (i.e., inconsistent or unpredictable outputs, but the program was not crashed), which implied fprintf had a lock to protect their internal data structure.

minjang
  • 8,860
  • 9
  • 42
  • 61
  • Multiple threads reading and writing to the same socket is, in my opinion, a de facto design problem. – theMayer Feb 12 '18 at 20:10

4 Answers4

10

Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation. Check this discussion for additional information.

EDIT: OS could have or couldn't have internal lock for protecting internal structures. It depends on implementation. So you should not count on it.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • 3
    Sounds like the POSIX send/recv is thread safe based on your link and on this discussion: http://stackoverflow.com/a/1981439/602245 – Brett Feb 10 '13 at 17:46
  • If one thread performs the `send` operation, another performs the `read` operation, will these two be thread safe? – mercury0114 Jul 12 '21 at 10:26
  • @mercury0114 yes, `send` and `read` use different buffers. Forking a socket into "reader" and "sender" is pretty common. – Ivan C Jul 29 '23 at 19:37
2

I find multiple socket close() file descriptor calls extremely dangerous in concurrent environment.

Usually multiple calls are ignored, but in case other thread opens another file descriptor, quite often it gets previous file descriptor, and nightmare starts.

0

No, the variable created with accept does not need to be mutex. Any data used by threads should at least be semaphores.

sem_t* sem_data;
frogatto
  • 28,539
  • 11
  • 83
  • 129
November
  • 224
  • 2
  • 11
0

Sending data via a socket is not a atomic transaction - any non-atomic transaction will require a lock/synchronisation. This is independent of the platform.

weismat
  • 7,195
  • 3
  • 43
  • 58