Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prioritized Auto-Reset Event

I have this problem: Thread1 may set an auto-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

like image 666
Armen Tsirunyan Avatar asked Feb 24 '11 13:02

Armen Tsirunyan


1 Answers

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.

like image 77
andersoj Avatar answered Sep 22 '22 11:09

andersoj