5
votes

write function calls from multiple threads to the same socket

is it safe ? Do we wanted to add a syncronization among them? Will it cause fro problems like Application getting delayed write/read from the Network Layer to Application layer

We are using GNU C++ libraries GCC 4 on Linux Redhat Enviornment

This is a Server Side Process where There is only 1 Socket Connectivity between Server & Client Server & Client are on 2 diffent Machines Data is send from Server to Client Client to Server

Problem 1-when Server Send Data to Client Side (Multiple Threads Write data to client Side through the Same Single Socket) But Data Writen from the some of the threads are not gone to client side it doesnot even gone to the network Layer of the same machine (Tcpdump does not have that data)

Problem 2-when Client Send data to Server Data Send By Client is shown in the the server's TCPdump not received for the server application which is reading from the socket from a single thread usinga "read" & "select" functions in a loop

We were unable to identify the pattern of occuring these Problems We think This happend when so many multiple threads are writing to Same socket We are not syncronizationed write function hoping that OS is handling the syncronization

3
It's "safe" in the sense that your program is well-formed, but the results that you see on your socket may not be what you expect.Kerrek SB
@KerrekSB: that's an odd comment. Any thread-unsafe program could be called "safe" in that sense, no?Ned Batchelder
@NedBatchelder: Surely not. For example, a function that depends on a static buffer for its internal state-keeping is simply not thread-safe, and a program that calls it multiple times concurrently is just ill-defined. By contrast, a program that calls write concurrently is not automatically ill-defined.Kerrek SB
possible duplicate of Socket send concurrency guaranteesselbie

3 Answers

1
votes

write() is a system call, not a library function, and system calls are generally guaranteed to be atomic.

0
votes

It is not safe to use write() from multiple threads. There is no guarantee that the output won't be shuffled together. One write could put half of its bytes onto the socket, then another write could start putting it bytes. If you need to be sure each write is written contiguously (and it's hard to imagine not needing that guarantee), then you need a lock or some other synchronization method.

0
votes

It would be unspecified which write call completes first. A context switch could stall any of the two writes at the first instruction. This can lead to arbitrary ordering. There is nothing write or the kernel can do about that. It is a fundamental problem.

Your data will be written in unspecified order which is probably not acceptable to you.