7

I have a single non-blocking socket sending udp packets to multiple targets and receiving responses from all of them on the same socket. I'm reading in a dedicated thread but writes (sendto) can come from several different threads.

Is this a safe without any additional synchronization? Do I need to write while holding a mutex? Or, do writes need to come from the same thread and I need a queue?

NY UPTOWN
  • 73
  • 1
  • 3

2 Answers2

8

The kernel will synchronize access to underlying file descriptor for you, so you don't need a separate mutex. There would be a problem with this approach if you were using TCP, but since we are talking about UDP this should be safe, though not necessarily best way.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • @Nicolai In this application there are several worker threads that "sense" the need to send a packet. Curious about your comment that this is not necessarily the best way -- what are the reasons for that? – NY UPTOWN Jun 26 '12 at 20:41
  • That all depends on the application at hand, but in general udp servers are so much easier and cleaner done *iteratively* with non-blocking sockets. – Nikolai Fetissov Jun 26 '12 at 20:46
  • 1
    @NY UPTOWN: It's OK to have multiple `sendto()s` from different threads race, but you should ensure that `sendto()` doesn't race with `close()`. – caf Jun 27 '12 at 05:54
  • @caf Good point about close. The logic is that some threads are started at initialization and then (using a condition variable) they are stopped and joined prior to close. – NY UPTOWN Jun 27 '12 at 13:14
-1

You can write to the socket from a single or multiple threads. If you write to a socket from multiple threads, they should be synchronized with a mutex. If instead your threads place their messages in a queue and a single thread pulls from the queue to do the writes, reads and writes to/from the queue should be protected by a mutex.

Reading and writing to the same socket from different threads won't interfere with each other.

Dave Rager
  • 8,002
  • 3
  • 33
  • 52
  • It's true that the mutex will serialize the requests but the difference is that writes will come from different threads vs. the same thread with a producer/consumer style queue. – NY UPTOWN Jun 26 '12 at 17:23