Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux socket using multiple threads to send

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?

like image 230
NY UPTOWN Avatar asked Jun 26 '12 17:06

NY UPTOWN


People also ask

Can multiple threads use the same socket?

No two threads can use the same Socket because of the Synchronize sections. So they're never mutating it at the same time.

Is Sendto thread-safe Linux?

Description. According to the documentation, instances of Socket. Send are thread-safe.

Is socket send thread-safe?

Writing to a socket by multiple threads is thread-safe as long as the other end can make sense of the intereleaved data. Reading from a socket by multiple threads is thread-safe as long as this end can make sense of the interleaved data.

What is multi threading Linux?

In Linux terminology, simultaneous multithreading is also known as SMT or Hyper-Threading. With multithreading enabled, a single core on the hardware is mapped to multiple logical CPUs on Linux. Thus, multiple threads can issue instructions to a core simultaneously during each cycle.


1 Answers

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.

like image 108
Nikolai Fetissov Avatar answered Oct 07 '22 00:10

Nikolai Fetissov