Reputation: 894
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)
Upvotes: 0
Views: 856
Reputation: 598134
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.
Upvotes: 1
Reputation: 27190
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.
Upvotes: 1
Reputation: 2695
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.
Upvotes: 1