I have an issue in using WaitForMultipleObjects on Anonymous Pipe. My goal is to Wait on a pipe to be written and another object at the same time. To be more precise, I am using pipes for local IPC. I saw on stackoverflow an approach where you can create a handle using CreateEvent and set this event whenever you have a WriteFile operation on the pipe and reset it after a ReadFile but here is a simple unit test that proofs that this approach is not correct.
#include <windows.h>
#include<iostream>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
HANDLE event_on_pipe;
HANDLE endpoint_pipe[2];
DWORD WINAPI WThread_Pipe( LPVOID lpParam )
{
ULONG buffer = 1234;
DWORD bytes;
int write;
int count = 10;
while(count --)
{
WriteFile(endpoint_pipe[1],(char*)&buffer, sizeof(buffer),&bytes,NULL);
if ( !SetEvent(event_on_pipe) )
{
printf("SetEvent failed (%d)\n", GetLastError());
return 0;
}
}
return 0;
}
int main()
{
HANDLE Thread_Pipe;
DWORD ThreadID_Pipe;
event_on_pipe = CreateEvent(NULL,FALSE,FALSE,NULL);
CreatePipe(&endpoint_pipe[0],&endpoint_pipe[1],NULL,0);
HANDLE lphandles[1];
lphandles[0] = event_on_pipe;
Thread_Pipe = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) WThread_Pipe, NULL, 0, &ThreadID_Pipe);
ULONG buffer;
DWORD bytes;
while(1)
{
DWORD obj = WaitForMultipleObjects(1,lphandles,FALSE,INFINITE);
if(obj == WAIT_OBJECT_0)
{
ReadFile(endpoint_pipe[0], &buffer,sizeof(ULONG),&bytes,NULL);
ResetEvent(event_on_pipe);
Sleep(1000);
}
std::cout << buffer<<std::endl;
}
return 0;
}
I am supposed to see on the console 1234 printed 10 times while I am seeing it two times. The main problem is that when I call the function Sleep for one second after ReadFile operation the thread "write the pipe and set the event" 9 times, So I still have 9 ReadFile operation left but since setting the event 9 times is considered as one set then WaitForMultipleObjects is going to be signaled once.
I want an efficient way to signal WaitForMultipleObjects when a pipe is written (for local inter process communication). It doesn't need to be an anonymous pipe, it could be something else that acts like pipes to exchange messages between threads. So if someone knows how it could be done please help.