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?

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@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?
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.
@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 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.
-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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.