C socket API是线程安全的吗? [英] C socket API is thread safe?

查看:246
本文介绍了C socket API是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Linux和Win32套接字API。在我的程序中,多个线程共享一个套接字句柄。特别地,多个线程用共享套接字句柄(即同一端口)调用 send 。在这种情况下,我必须为线程安全设置锁吗?我找不到答案。我可以做一个测试,但想听听你的经验。



EDIT :我知道通过socket发送数据不是原子操作在所有。绝对我们必须使用互斥体来保证线程安全。但是,我想知道系统API是否可以有自己的内部锁。如果是这样,我们可以省略自己的锁。



此问题也适用于 fprintf 函数。我想知道这样的系统API会有自己的锁。在我的经验,从多线程调用 fprintf 没有杀死我的程序,虽然有文件或stdout上的比赛(即不一致或不可预测的输出,但程序不是崩溃),这意味着 fprintf 有一个锁来保护其内部数据结构。

解决方案

套接字不是C ++ Standard的一部分,因此它取决于实现。通常,它们不是线程安全的,因为 send 不是原子操作。有关其他信息,请查看此讨论。 p>

编辑:操作系统可以具有或不具有用于保护内部结构的内部锁。这取决于实施。所以你不应该指望它。


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.

解决方案

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.

这篇关于C socket API是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆