Reputation: 342
I have to do OperationA on input files( 1...N), after that I have to do OperationB on operationA completed files.
So in the main thread I iterated through each files( 1...N) and do the operationA. Then pushes the files to a threadsafe queue and continue for next files. A worker thread gets the files from queue and do operationB. To implement this I used events like the following:
HANDLE hEvent =CreateEvent(NULL, FALSE/*autoreset*/, FALSE/*nonsignaled*/, "");
for( files 1... N)
{
1. Operation A
2. Push file to the queue
3. SetEvent( hEvent )
}
WorkerThread()
{
while(1)
{
1. WaitforSingleObject( hEvent , INFINITE )
2. operation B
}
}
What I am expecting is for each SetEvent() the WaitforSingleObject() will be signaled. But the actual behavior is not. I.e For the first SetEvent the WaitforSingleObject is signalled. While the operationB is in progress many SetEvents are triggering from main thread. So the next WaitforSingleObject() should signal with out any delay, since the second SetEvent is already trigerred. But this is not working as expected.
I called 6 setevent for 6 files. But WaitforSingleObject is signaled for only 3.
First of all please let me know am I using the correct synchronization mechanism for the context?
Upvotes: 2
Views: 137
Reputation: 1519
This is producer-consumer problem, and you can do it with semaphores.
Check this link https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem
Your code is inadequate implementation in the link.
With Semaphores the code will run as expected.
Upvotes: 2