c++ - 用于线程间通信的 Windows 套接字

标签 c++ multithreading sockets synchronization winsockets

我有一个等待阻塞调用(通过选择)的线程,并希望它同时与父线程通信。因为,当父级向它发送消息时它可能会参与阻塞调用,所以我不能使用 WaitForMultipleObjects。我想知道我是否可以在子线程和父线程之间使用套接字,但所有文献都表明套接字最好用于进程间而不是线程间通信。同时,我找不到它们可能不适合我的用例的原因。是否有任何我可能遗漏的东西,或者是否有针对此类用例的其他解决方案。 (寻找基于 C++ 的解决方案)

最佳答案

I have a thread that waits on a blocking call (via select) and want it to communicate with the parent thread at the same time. Since, it can be involved in a blocking call when parent sends it a message, I cannot use WaitForMultipleObjects.

您不能使用 WaitForMultipleObjects() 来等待 SOCKET 句柄。

但是,如果您使用 WSAEventSelect() 而不是 select() 来等待套接字操作,那么您可以使用 WaitForMultipleObjects()WSAWaitForMultipleEvents() 同时等待套接字事件以及其他 Win32 对象,如事件对象、管道等。

或者,如果您可以使用 PostThreadMessage() 在线程之间发布消息,您可以使用 MsgWaitForMultipleObjects()相反。

否则,您只需在短时间内调用 select(),然后在 select() 调用之间根据需要检查您的线程间通信.

I was wondering if I can use a socket between child and parent thread

从技术上讲是的,但这样做并不是很有用。线程之间有更有效的通信方式。

all literature suggests that sockets are best used for inter-process and not inter-thread communication.

没错。

关于c++ - 用于线程间通信的 Windows 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50905080/

相关文章:

c++ - 使用 SolidWorks API 将装配体另存为零件时出现 swGenericSaveError (C++)

c++ - 使用 stdin stdout 和 stderr 启动 exe/进程?

java - gRPC 服务器能否立即回收 DEADLINE_EXCEEDED 线程?

multithreading - JavaFX 从 Controller(Singleton) 访问 ui 元素

c - c中的socks代理身份验证

c++ - 有没有办法在 Visual Studio 2019 中加载当前 .cpp 文件的 .h 文件?

android - 使用 FFmpeg 捕获视频流

c# - Windows Forms .NET 中的 DataGridViewRow 线程安全

PHP客户端Web socket发送消息

c# - 我应该在套接字接收和另一个之间使用 Thread.Sleep 吗?