Are sockets thread safe?

Is it safe to send from multiple threads at the same time?

I have a single thread that listens for new messages and then spawns a new thread for each request.
Should I lock when sending the response?
What would be the point of sharing a single connection between multiple server threads? A single connection can only transfer data serially.
If you want to allow a single client to make multiple concurrent requests, accept n connections from the same socket and associate a thread to every connection.
It is safe to use different sockets concurrently.
I think both of you misunderstood the situation.

I'm specifically talking about one UDP socket that recv() some data, spawns a new thread and send() the response from that new thread.

The question is should I use a lock when using the send() function?
Oh. kbw's answer is still valid, AFAIK.
> I'm specifically talking about one UDP socket that recv() some data, spawns a new thread and
> send() the response from that new thread. The question is should I use a lock when using the send() function?

A lock is not required; send() is a syscall, it is an atomic operation with no race conditions in the kernel.

Note that datagram sockets (UDP) are connection-less, so the the datagram packets may be delivered in a sequence that is different from the sequence in which they were sent (even if all the send calls were from within a single thread).

For stream sockets (TCP) too, the send() function is atomic; but there is no concept of distinct messages or packets, the data treated as a single stream of bytes. So even though send() is thread-safe, synchronisation is required to ensure that the bytes from different send calls are merged into the byte stream in a predictable manner.
Thanks for the info!
Topic archived. No new replies allowed.