Is accept() thread-safe?
Yes. This is a common way to design multithreaded servers and accepted design practice.
You can also fork
several times and have the child processes call accept
, this will allow you to do multithreading without needing a threads library. Older servers do this.
Since this has been bountied, asking for references:
Yes, accept()
is thread-safe, as POSIX defines that term.
The relevant reference would be section 2.9.1 of POSIX.1, the current version of which says:
All functions defined by this volume of POSIX.1-2017 shall be thread-safe, except that the following functions need not be thread-safe.
[a list that does not include
accept()
]
For completeness, POSIX does define accept()
: https://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html, so as a POSIX function that does not appear on the list of exceptions, POSIX specifies that it is thread-safe.
In comments, @Rick (the bounty offerer) says:
In some ways I get the point now. thread-safe would be the property that meets the behaviour. I was thinking thread-safe has to be threads within same process. But now I think there aren't much differences between threads within same process or threads between different processes. In some ways they are the same. So the concept of thread-safety can be applied to both scenarios.
The POSIX definitions regarding thread-safety do indeed refer to threads in the same process (see: §2.9).
If you are asking about what happens after fork()
, and if it is safe for the parent and child to concurrently call into accept()
, we note first that POSIX defines a system resource known as a connection indication queue. Then we note that the child of fork()
gets a copy of the parent's descriptors, and therefore the child and parent will access the same connection indication queue (just as a duplicate file descriptor to a text file would be accessing the same file).
The definition of what accept()
does for each process (child and parent) is the same at that point.