2

I'm using a semaphore to control access of multiple concurrent threads.

It would be nice if the semaphore could preferably enable those threads that have waited the longest, instead of just randomly picking one. In other words, it should have some notion of fairness.

The documentation on semaphores mentions they are not fair:

There is no guaranteed order, such as FIFO or LIFO, in which blocked threads enter the semaphore.

How should I go about creating such a semaphore?

mafu
  • 31,798
  • 42
  • 154
  • 247
  • 1
    The MSDN docs state it is *not* fair for `SemaphoreSlim`: "there is no guaranteed order, such as FIFO or LIFO, that controls when threads enter the semaphore." See [this thread](http://stackoverflow.com/questions/2553982/guaranteed-semaphore-order) for potential solutions. – vcsjones Nov 16 '16 at 23:13
  • @vcsjones I'm using a regular `Semaphore`, but that's good to know. – mafu Nov 16 '16 at 23:15
  • @vcsjones Oh, I just noticed it does mention the same for the regular one, too! I missed that. – mafu Nov 16 '16 at 23:16
  • it also says that for the Win32 semaphore APIs, which `Semaphore` is just a wrapper around. " Do not assume a first-in, first-out (FIFO) order" https://msdn.microsoft.com/en-us/library/windows/desktop/ms685129(v=vs.85).aspx – vcsjones Nov 16 '16 at 23:17
  • @vcsjones Thank you. I've edited the question to how to create such a semaphore, seeing you already answered my initial question! :) – mafu Nov 16 '16 at 23:18

0 Answers0