我有一个等待阻塞调用(通过选择)的线程,并希望它同时与父线程通信。因为,当父级向它发送消息时它可能会参与阻塞调用,所以我不能使用 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/