Lock Statement C#

Say I have three threads that need access to a collection and I use a lock block around the access in each thread. The following happens...

(1) Thread 1 gets the lock on the collection
(2) Thread 2 gets blocked
(3) Thread 3 gets blocked

When Thread 1 releases the lock, who gets to take the lock next? Is it FIFO access?

Thanks

Upvotes: 6

Views: 2940

Answers (5)

Dirk Vollmar
Dirk Vollmar

Reputation: 176159

Your question implies that you are looking for a FIFO behaviour? Then you might want to try this code by Jakub Sloup:

Monitor/lock which remember order in C# to simulate FIFO

As already mentioned in the other answers there is no guaranteed order waiting threads will receive a lock.

Upvotes: 5

C. Ross
C. Ross

Reputation: 31848

The answer is by definition, indeterminate.

Upvotes: 3

Spence
Spence

Reputation: 29322

As an answer to your question, all threads recieve the monitor.pulse which will then fight over who gets the lock next.

I believe that the people at wintellect wrote a blog regarding how this behaviour could lead to an unfair situation, but there is no fairness at all in the monitor.

Upvotes: 4

ChrisW
ChrisW

Reputation: 56083

Assuming it's like Win32 then the answer is that it might be FIFO but it might not (it be something else). For example, a higher-priority thread should be first; but threads can get a temporary boost or drop in their priority depending on what they've been doing recently.

Upvotes: 4

Amy B
Amy B

Reputation: 110071

You should not care who gets the lock next.

Upvotes: 17

Related Questions