Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C socket API is thread safe? [duplicate]

I'm using both Linux and Win32 socket APIs. In my program, multiple threads share a socket handle. In particular, multiple threads call send with the shared socket handle (i.e., the same port). In this case, do I have to put a lock for thread safety? I was unable to find the answer. I may do a test, but want to hear your experiences.

EDIT: I know that such sending data via socket isn't atomic operation at all. Definitely we have to use a mutex for thread safety. However, I was wondering whether the system API could have their own internal lock. If so, we can omit putting our own lock.

This question may be applicable to fprintf function as well. I'm wondering such system APIs would have their own locks. In my experience, calling fprintf from multiple threads didn't kill my program although there was races on a file or stdout (i.e., inconsistent or unpredictable outputs, but the program was not crashed), which implied fprintf had a lock to protect their internal data structure.

like image 300
minjang Avatar asked Mar 01 '10 07:03

minjang


People also ask

Are C sockets thread-safe?

Generally they are not thread safe since send is not an atomic operation.

Can multiple threads write to the same socket?

Indeed your design does allows several Threads to obtain the same Socket handle.

Is Sendto thread-safe Linux?

Send are thread-safe. This is reliably the case on Windows. When running the same code on Linux, sporadically, the data that is received by the receiving party seems to be partially scrambled when Socket. Send is called from multiple threads concurrently.

Is ++ thread-safe in C?

++ is not defined as thread-safe.


2 Answers

Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation. Check this discussion for additional information.

EDIT: OS could have or couldn't have internal lock for protecting internal structures. It depends on implementation. So you should not count on it.

like image 147
Kirill V. Lyadvinsky Avatar answered Sep 18 '22 13:09

Kirill V. Lyadvinsky


I find multiple socket close() file descriptor calls extremely dangerous in concurrent environment.

Usually multiple calls are ignored, but in case other thread opens another file descriptor, quite often it gets previous file descriptor, and nightmare starts.

like image 36
MajstorKvaris Avatar answered Sep 22 '22 13:09

MajstorKvaris