gpt4 book ai didi

c++ - winsock2线程安全吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:04 24 4
gpt4 key购买 nike

我正在编写一个包含 3 个服务器和 1 个客户端的小型程序。 2 个服务器发送 tcp 消息,最后一个使用 winsock2 发送 upd 数据报。

我想知道我是否可以通过使用线程(OpenMP 或 boost::threads)进行同步 recvfrom(),以便 2 个线程同时从同一端口上的同一套接字监听。

我在 windows7 上使用 VC++ 2010。

感谢您的帮助。

最佳答案

是的,套接字是线程安全的,但是您必须小心。一种常见的模式(当使用阻塞 IO 时)是让一个线程在套接字上接收数据,而另一个线程在同一个套接字上发送数据。让多个线程从一个套接字接收数据通常对 UDP 套接字没问题,但大多数时候对 TCP 套接字没有多大意义。 WSARecv 的文档中有警告:

WSARecv should not be called on the same socket simultaneously from different threads, because it can result in an unpredictable buffer order.

但如果您使用的是 UDP 并且该协议(protocol)是无状态的,那么这通常没有任何问题。

另请注意,WSAEINPROGRESS 错误代码主要适用于 Winsock 1.1:

WSAEINPROGRESS: A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

WSAEINPROGRESS 的描述进一步指出:

Operation now in progress.

A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.

请注意,这里讨论的是每个任务或线程的单个阻塞操作。

此外,在 WSARecv 的文档中还有一个额外的警告:

Issuing another blocking Winsock call inside an APC that interrupted an ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.

但除了这些警告之外你应该没问题。

更新:添加一些外部引用: alt.winsock.programming: Is socket thread-safe?Winsock Programmer’s FAQ: Is Winsock thread-safe?

关于c++ - winsock2线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13983398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com