简体   繁体   中英

Concurrent system calls in Linux

Simple as this question is, I haven't found anything about it by Googling. Is it safe to make concurrent calls to the Linux system, such as calling socket() on several threads at (what might be) the same time? Specifically, does the kernel guarantee thread-safety for socket() , connect() , and/or send() ?

If not, why not? I'd really like to learn more about this topic and why system calls are or are not thread-safe.

My main concern here is really that socket() will not return a duplicate or invalid file descriptor when called from different threads. I'm not going to be connecting or writing to the same socket at the same time in my case.

Is it safe to make concurrent calls to the Linux system, such as calling socket() on several threads at (what might be) the same time?

Yes, they are thread safe. Though I am not sure its just as per the POSIX standard or not.

Specifically, does the kernel guarantee thread-safety for socket(), connect(), and/or send()?

As per THIS link, yes. It says that locks are used internally, which would mean that your send operation would be serialized, but not in any specific order.

Answer to updated part of the question:

My main concern here is really that socket() will not return a duplicate or invalid file descriptor when called from different threads.

No worries here. OS will make sure that the file descriptors for the socket are not duplicated.

"Will you crash the system?" No.

"Might your threads 'race' and otherwise 'compete' with one another, such that you get thoroughly unpredictable and un-reproducible results? Definitely yes.

The kernel generally views resources (such as sockets ...) as being owned by the process to which all the threads belong. And, if a particular call is "blocking," it's probably going to block the process.

Finally, socket actions, such as send , really don't benefit from the use of threads anyway, because packets are being sent and received through a (comparatively slow ...) single wire, one at a time, at millisecond speeds. A simple select() polling-loop generally works just fine. "Complexity won't be re-paid."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM