C 套接字 API 是线程安全的吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2354417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C socket API is thread safe?
提问by minjang
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.
我同时使用 Linux 和 Win32 套接字 API。在我的程序中,多个线程共享一个套接字句柄。特别是,多个线程send
使用共享套接字句柄(即同一个端口)调用。在这种情况下,我是否必须为线程安全加锁?我无法找到答案。我可能会做一个测试,但想听听你的经验。
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.
编辑:我知道这种通过套接字发送数据根本不是原子操作。当然,我们必须使用互斥锁来保证线程安全。但是,我想知道系统 API 是否可以拥有自己的内部锁。如果是这样,我们可以省略放置我们自己的锁。
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.
这个问题也可能适用于fprintf
函数。我想知道这样的系统 API 会有自己的锁。根据我的经验,fprintf
虽然文件或标准输出存在竞争(即不一致或不可预测的输出,但程序没有崩溃),但从多个线程调用并没有杀死我的程序,这意味着fprintf
有一个锁来保护它们的内部数据结构.
回答by Kirill V. Lyadvinsky
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 discussionfor additional information.
套接字不是 C++ 标准的一部分,因此它取决于实现。通常它们不是线程安全的,因为send
不是原子操作。查看此讨论以获取更多信息。
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.
编辑:操作系统可以有或不能有用于保护内部结构的内部锁。这取决于实施。所以你不应该指望它。
回答by MajstorKvaris
I find multiple socket close() file descriptor calls extremely dangerous in concurrent environment.
我发现多个套接字 close() 文件描述符调用在并发环境中非常危险。
Usually multiple calls are ignored, but in case other thread opens another file descriptor, quite often it gets previous file descriptor, and nightmare starts.
通常多次调用会被忽略,但如果其他线程打开另一个文件描述符,它通常会获取以前的文件描述符,然后噩梦开始。
回答by November
No, the variable created with accept does not need to be mutex. Any data used by threads should at least be semaphores.
不,用accept 创建的变量不需要是互斥锁。线程使用的任何数据至少应该是信号量。
sem_t* sem_data;
回答by weismat
Sending data via a socket is not a atomic transaction - any non-atomic transaction will require a lock/synchronisation. This is independent of the platform.
通过套接字发送数据不是原子事务 - 任何非原子事务都需要锁定/同步。这与平台无关。