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

人盡茶涼 提交于 2019-12-25 04:19:47

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5039679/how-to-substitute-at-runtime-the-waithandle-that-a-thread-should-wait-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!