Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux C/C++ socket send in multi-thread code

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?

like image 770
Daniel Avatar asked Oct 30 '11 00:10

Daniel


People also ask

Can multiple threads use the same socket?

No two threads can use the same Socket because of the Synchronize sections. So they're never mutating it at the same time.

Can you multi thread in C?

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.

Does socket programming support multi programming?

@asma, yes. Both clients can run on the same machine. Many clients can run on a single machine or multiple machines.

How do you create multiple clients in socket programming?

The simple way to handle multiple clients would be to spawn new thread for every new client connected to the server.


1 Answers

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.

like image 164
sarnold Avatar answered Nov 15 '22 21:11

sarnold