3

I am currently developing a networking software that uses a datagram socket (UDP) to send data to clients. Whenever I'd like to send data to a client I am currently invoking sendto() and passing the respective parameters. Yet I am wondering whether or not making a blocking call to sendto() from multiple threads at the same time is good idea or whether data might get interleaved or corrupted in some other way.

I have already found this answer: is winsock2 thread safe? but I am not sure if this holds true for sendto() as it does for send()

Community
  • 1
  • 1
BlackyPaw
  • 33
  • 6

2 Answers2

1

System calls are not atomic, you can't assume they are thread safe. Thread safety depends on the system implementation. But thread safety just means you won't encounter crashes or memory corruption, it doesn't tell you anything about the behaviour. For example, you may have data interleaved in what you sent, with no respect to your threads calling order.

If you're working on Windows, Winsock2 seems to be thread safe on recent versions of the os. But once again, it doesn't mean it'll behave as you expect.

Rather than using several threads to send to or receive from a socket, you should consider using IO ports, which are meant for multithreading and asynchronous processing.

Nicolas Riousset
  • 3,447
  • 1
  • 22
  • 25
  • Thank you for the hint on IO completion ports! I should be able to build a working solution using them. – BlackyPaw Sep 02 '15 at 14:30
-2
  1. It is a system call, and system calls are atomic, and therefore thread-safe.
  2. It is UDP, and UDP send()/sendto()/sendmsg() sends a single datagram, and UDP guarantees datagram integrity, if it arrives at all.

But IMHO two threads writing to the same socket is probably never going to work at the application level without extreme care at a higher level.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    "system calls are atomic" Not in general and not even thread-safe in general. All the system has to promise is that no program can corrupt any other. – usr Sep 01 '15 at 10:48
  • As @usr already said, system calls are not necessarily atomic! I suggest you to please fix your answer. This appears to be a poor answer, please fix it. – Am_I_Helpful Sep 01 '15 at 12:25
  • @usr System calls are atomic on every operating system I have ever used in 49 years. If you have an exception please produce it. And specifically if you can produce a system than can interleave UDP datagrams please so so. – user207421 Apr 18 '20 at 06:14