How to substitute at runtime the WaitHandle that a thread should wait on

202 views Asked by At

I'm wondering how to safely change at runtime the EventWaitHandle that a thread should wait on.

Suppose for instance that there are two threads (A and C) that are synchronized through EventWaitHandles. A does its job cyclically and C waits until it receives notification from A that it can start doing its job (e.g. by the AutoResetEvent). The pattern is A-C-A-C...

Later on a new thread (B) is launched (e.g. by user action) and its job should be executed in between the two preexistent threads in this way: A makes its job, then signals B and once B finishes it signals C. Now the pattern is A-B-C-A-B-C...

So before thread C was waiting on the EventWaitHandle shared with A and later there should be a safe mechanism that makes C waiting on another EventWaitHandle shared with B. It seems to me that the tricky part is substituting the EventWaitHandle used by C, since once this is done I should easily be able to launch B that will use a EventWaitHandle to wait on A job and a EventWaitHandle to signal for C job. The mechanism should also provide a way to safely unmount thread B and to go back to the initial situation where only thread A and C are working.

Is there a safe way to accomplish this with EventWaitHandle ? If not, any other suggestion would be appreciated.

2

There are 2 answers

1
Anthony Williams On BEST ANSWER

If task A knows about the change, then have task C own the event. Task A signals task C's event if C is to be next, or task B's event if task B is to be next.

Alternatively, use the same mechanism as for changing any other shared data: acquire a mutex across all accesses to the handle. e.g. task C acquires the lock, reads the handle, releases the lock, waits on the handle. To change it you have the UI thread acquire the lock, change the handle, release the lock.

0
digg On

Have you thought about implementing some sort of scheduler where the threads can register (deregister) with a handle to start and to signal completion. And the scheduler then takes care of starting the next thread by setting the appropriate start-event and continues with the next thread, when the previous one has set the completion event.