c++multithreadingsocketssynchronizationwinsockets

Windows Sockets for inter-thread communication


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. I was wondering if I can use a socket between child and parent thread, but all literature suggests that sockets are best used for inter-process and not inter-thread communication. At the same time I dont find a reason of how they may not fit my use case. Is there anything I may be missing or is there another solution for such a use case. (Looking for a c++ based solution)


Solution

  • 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.

    You cannot use WaitForMultipleObjects() to wait on a SOCKET handle.

    However, if you use WSAEventSelect() instead of select() to wait on a socket operation, you can then use WaitForMultipleObjects() or WSAWaitForMultipleEvents() to wait on the socket event along with other Win32 objects at the same time, like event objects, pipes, etc.

    Or, if you can use PostThreadMessage() to post messages between threads, you can use MsgWaitForMultipleObjects() instead.

    Otherwise, you will just have to call select() with a short timeout, and then check your inter-thread comms as needed in between calls to select().

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

    Technically yes, but it is not very beneficial to do so. There are more efficient ways to communicate between threads.

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

    That is correct.