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)
Windows Sockets for inter-thread communication
790 Views Asked by rajat AtThere are 3 best solutions below
On
Set a timeout for select and run it in a loop so you can periodically communicate with the parent thread via memory.
Or run the select in a separate third thread and wait for it in the second thread using a std::condition_variable with a timeout in a loop or other means, while also being able to communicate with the parent thread.
On
wondering if I can use a socket between child and parent thread
Yes. You can.
but all literature suggests that sockets are best used for inter-process
The main reason (maybe the only reason) for choosing to use multiple threads within one process instead of using multiple processes to implement an application, is that the threads can communicate with one another through shared memory. This can simplify the design of the application because data do not have to be marshalled, and sent through pipes, and un-marshalled at the other end.
You cannot use
WaitForMultipleObjects()to wait on aSOCKEThandle.However, if you use
WSAEventSelect()instead ofselect()to wait on a socket operation, you can then useWaitForMultipleObjects()orWSAWaitForMultipleEvents()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 useMsgWaitForMultipleObjects()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 toselect().Technically yes, but it is not very beneficial to do so. There are more efficient ways to communicate between threads.
That is correct.