views:

281

answers:

3

I have two C++ processes (A and B), executing under Windows, where one launches the other. I would like to effectively single-thread their execution. For example:

  1. Start process A
  2. A creates B
  3. A suspends
  4. B executes some fixed set of operations
  5. B suspends and A is resumed
  6. A executes some fixed set of operations
  7. A suspends and B is resumed
  8. (Repeat 4 - 7)

Which Windows synchronization and IPC services would be best to implement this type of behavior?

A: 

For interprocess synchronization you could use semaphores. Here is the documentation.

Bogdan Maxim
Semaphores are just one tool. Mutexes and events may be more appropriate (and yes, I know you can probably implement those using semaphores...)
Roddy
I would probably use a semaphore (actually two: one in each direction) for this, unless there were unstated complications to prevent that. But it's false that you "need" to use semaphores.
Steve Jessop
+2  A: 

Pass two event handles (CreateEvent) to process B. signal one handle when process a is done working, signal the other when process b is done working. Each process calls WaitForSingleObject() to wait for the other process to finish a set of work.

Chris Becke
I assume when @Chris says pass two event handles, he means by unique name.
kenny
Create the handles as inheritable, and pass them by value. inheritable handles are 'duplicated' in the new process with the same value as they had in the old process.
Chris Becke
+6  A: 

Events would work in this case:

  • A creates an event an starts Process B
  • A waits for the event to be signaled
  • B also creates an event, does it's first item, then signals A's event (which either has a well-known name or the handle can be passed to B when it starts or using some other mechanism
  • B waits on its event
  • when A resumes from waiting on its event, it does its work, signals B's event and waits on its own
  • so on...

Just be sure you have error handling so each process can resume and do whatever is necessary if the other one hangs or terminates unexpectedly. Timeouts can handle the hang situation, and waiting on the other process's handle (using WaitForMultipleObjects() along with both the process and event handle) can determine if/when the other process terminates.

Michael Burr
One thing to bear in mind is that if the processes aren't running with the same priority, then you might want to use a synchronization primitive with priority-inversion avoidance. Same applies if they hold global locks while waiting on the other process. It's often not necessary, though.
Steve Jessop