tags:

views:

1700

answers:

5
+2  Q: 

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

+16  A: 

You should not care who gets the lock next.

David B
You might extend that to say you *cannot* care. Maybe.
JMD
I realize that I should program the threads so that I don't care, I'm just wondering what the mechanism is.
Jason Punyon
http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx#vcwlkthreadingtutorialexample4mutex"The speed and operating system of the machine running the sample can affect the output order."
David B
+3  A: 

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.

ChrisW
From what I have read, this is correct. Lock can be thought of FIFO, but it is not guaranteed.
Mike_G
+5  A: 

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.

0xA3
+3  A: 

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.

Spence
+3  A: 

The answer is by definition, indeterminate.

C. Ross