4

Looked around, but could not find any link justifying the answer for AF_UNIX sockets.

My implementation is on a linux system, I have an AF_UNIX SOCK_STREAM socket,

  • one receiver thread on this socket
  • few worker threads which can call 'send()' on this socket.

My question is - are AF_UNIX socket 'send()' thread safe? If I have threads parallely/concurrently calling send on the AF_UNIX socket fd, will kernel take care of the synchronization?

I went through multiple links, but all are related to TCP/UDP (AF_INET) sockets, so if anyone could suggest a link that justifies the answer, or could provide some insight into the kernel code, it would be of great help.

peterh
  • 11,875
  • 18
  • 85
  • 108
greenhorn
  • 41
  • 1
  • 3

2 Answers2

6

POSIX specifies that all functions it defines must be thread-safe, except those on a list of specific exceptions. The send(2) function is defined by POSIX and is not included on the list of exceptions. Inasmuch as the Linux implementation of send(2) purports to conform to POSIX specifications, you can rely on it to be thread-safe.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 2
    As far as I know, "Linux" is not a "POSIX-compliant system". –  Nov 19 '15 at 19:40
  • 1
    @Rhymoid, `send()` is a syscall, and its Linux implementation in is documented to conform to POSIX. I have updated my answer to be more precise in that regard. – John Bollinger Nov 19 '15 at 19:50
  • Yes but what does "thread safe" mean? – curiousguy Nov 19 '15 at 20:20
  • @curiousguy, as far as POSIX is concerned, a function being thread-safe means that if that function is called concurrently by two different threads, then the behavior of each call is consistent with the specifications for the function. – John Bollinger Nov 19 '15 at 20:51
1

In general, operations like read or write are atomic. But on pipes or sockets things are different.

For pipes, POSIX, but I suspect Linux to be compliant on that point, states that concurrent writes are guaranteed not be interleaved only if length is less than PIPE_BUF. See POSIX write.

For sockets, Linux manual for send family functions says:

When the message does not fit into the send buffer of the socket, send() normally blocks, unless the socket has been placed in nonblocking I/O mode.

This suggests that the kernel probably sends your message into pieces, just like with pipe semantic.

There exists a provided answer on this subject Is send atomic?.

Community
  • 1
  • 1
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69