In standard C# synchronization classes (like Monitor), if several threads wait on some object to be unlocked, no one can predict which thread will get the next lock.
I want to assign priority to all waiting threads, so they get locks according to this priority (if several threads wait for unlock).
How can I implement that?
The simplest approach, if there aren’t too many priority levels, would be to have a main lock plus an Int32 for each level except the highest indicating how many tasks of higher priority are waiting. A task that wants to acquire the lock would Interlocked.Increment the counter for each lower priority, then wait on the main lock and check to see whether any higher-priority tasks were waiting. If so, it would release and reacquire the main lock. Otherwise, Interlocked.Decrement the counters of lower-priority tasks, use the resource, and release the main lock. If the routine gives up on acquiring the lock, it should decrement the counters of lower-priority tasks.
This approach would have some extra overhead from lower-priority tasks acquiring and releasing the master lock while higher-priority tasks wanted it, but it shouldn’t be too bad. Further, the order in which lower-priority tasks acquire a lock after a higher-priority task is done with it could be effectively random. Such issues could be avoided by adding a lock for each priority level, and having each task acquire the lock for its level after the Interlocked.Increment operations; as before, the Decrement should happen when the lock either acquires the resource or gives up on waiting for it.