Reputation: 1896
I am using a socket and this will be use in multithread environment where many thread will write on same socket. Does socket it-self synchronize it or I have to use mutex?
Will one trher will be block if another one is writing on it?
Upvotes: 3
Views: 1206
Reputation: 73081
Sharing a socket across threads without synchronization is safe in the sense that your data won’t be lost and it won’t cause your program to crash; for sending UDP packets it might be a reasonable thing to do. For TCP it’s often less useful since the ordering of the data being sent across the TCP stream won’t be well-defined and therefore it will likely be difficult or impossible for the receiver to parse correctly.
Note that if multiple threads have unsynchronized access to the socket it becomes difficult to close the socket safely; you would probably need to keep the socket open until after all the threads have exited, in order to avoid the possibility of the socket’s file descriptor being accessed after the socket was closed.
Upvotes: 1
Reputation: 1156
For single write it is atomic. The catch is message ordering (including interleaved message) at receiving side. If it is needed then you need locking. If you don't want to spend too much time on the lock. You can use producer/consumer pattern to decrease locking time.
Upvotes: 1