开发者

Prioritized Auto-Reset Event

I have this problem: Thread1 may set an au开发者_如何学Goto-reset event, and there are many threads that may wait for the event. Is there any way I can specify the priority of the waiting threads for the specific event, that is, if say the event is set and both A and B are waiting for it, I want to make sure that B will work, and A will wait for the next chance. Any synchronization objects for this? Language is not so relevant.

Thanks in Advance


The problem as you describe it requires real-time scheduler and synchronizer. While I understand that such things exist in the Windows API, I have tried very hard to avoid knowing about them.

My recommendation, unless the rest of the system is a true real-time system, would be to roll your own solution using a priority queue. Ensure that each thread communicates its effective priority to the queue when registering, block that thread on a condvar, and arrange it such that, when the event occurs, it is only delivered to the first thread on the queue.

There is likely to be a bit of ugly hacking in here, but if the thread count is low, you can do some kind of brute-force thing w/ one condvar per waiting thread and make it work.

Depending on what you need, consider this: Every event-receiver thread has an associated event queue (maybe it's really a mailbox; a 1-deep queue) with mutex and condvar. When threads register to receive the event, they are added to a priority queue as above and then block. When the event occurs, the event deliver thread chooses the highest-priority queue member, removes it, delivers the event notification to the individual thread's event queue, waking up the thread.


If thread A has a higher priority than thread B then the scheduler will choose to wake A in preference to B most of the time. You can use SetThreadPriority to change the priority of the threads.

It is usually considered better to write your code so that whichever thread gets woken the same work gets done --- the most important work, whatever that is. Then, the scheduler can choose whichever thread is most convenient for it, and the same work gets done

If you have multiple threads and it is imperative that an event is processed by a particular thread then have an event specially for that thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜