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?
No two threads can use the same Socket because of the Synchronize sections. So they're never mutating it at the same time.
C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.
@asma, yes. Both clients can run on the same machine. Many clients can run on a single machine or multiple machines.
The simple way to handle multiple clients would be to spawn new thread for every new client connected to the server.
It depends upon which primitives you're using to submit data to the socket.
If you're using write(2)
, send(2)
, sendto(2)
, or sendmsg(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 the sendfile(2)
operation "writes" the entire contents of the file to the socket before any other write(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With