2

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.

  • SetEvent
    • WaitforSingleObject
  • SetEvent
  • SetEvent
  • SetEvent
    • WaitforSingleObject
  • SetEvent
  • SetEvent
    • WaitforSingleObject

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?

aks
  • 302
  • 2
  • 10
  • what libraries are you going to include? – Arash Nov 16 '17 at 05:21
  • 2
    Event is basically just a boolean flag. Calling `SetEvent` on an event that's already set is a no-op. Just have your worker thread handle all the queue items until the queue is empty, whenever it wakes up. – Igor Tandetnik Nov 16 '17 at 05:30
  • If you haven't left it out to simplify your example, you'll probably want some protection, a mutex or what-have-you, around queue. – user4581301 Nov 16 '17 at 05:44
  • @ Arash Mohammadi - Win32/STL – aks Nov 16 '17 at 05:56
  • It all depends on your implementations, which are not clear enough from your question. How does your signaling system work? Do you store a queue of events that the worker can check every time it completes the current task? – Emerald Weapon Nov 16 '17 at 08:06

1 Answers1

2

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.

CodingLab
  • 1,441
  • 2
  • 13
  • 37
  • 1
    Thank you for pointing out the real problem. Also the below link helped me to resolve the producer-consumer problem. https://stackoverflow.com/questions/9396279/consumer-producer-in-c – aks Nov 16 '17 at 23:39