In a multi-thread code, if there are several threads trying to send data to a tcp socket at the same time, what will happen? will their data be mixed or will different threads will end up sending data one by one?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends upon which primitives you’re using to submit data to the socket.
If you’re using
write(2),send(2),sendto(2), orsendmsg(2)and the size of your message is small enough to fit entirely within the kernel buffers for the socket, then that entire write will be sent as a block without other data being interspersed.If you’re using
fwrite(3)(or any other higher-level buffered IO abstraction), then there is a chance that your data will be sent without any other data being interspersed, but I would not rely upon this behavior.I can’t speak to
sendfile(2)behavior. I’d like to think that thesendfile(2)operation “writes” the entire contents of the file to the socket before any otherwrite(2)requests on the socket, but the documentation I’ve read doesn’t say a word about it, so you better not make the assumption that it is in any sense “atomic”.The safest mechanism is for only a single thread to ever be submitting data to a socket.