c# - How does the Lock statement determines the order of granting object access? -
this question has answer here:
i require section of code run 1 thread @ time (single resource lock).
the lock(object)
statement in c# allows this. doesn't however, preserve order of requests lock.
for example, consider 100 threadstarts below numbered threads try lock on padlock in order:
(int = 0; < 100; i++) { (new thread(delegate(object index) { int name = (int) index; byte[] len = new byte[2]; console.writeline(string.format("thread:{0} going lock. ", name)); lock (padlock) { rnd.getbytes(len); ushort l = bitconverter.touint16(len, 0); console.writeline(string.format("thread:{0} sleeping: {1}", name, l)); thread.sleep(l); } })).start(i);
the actual granting of access not in perfect order (1->100) or not fifo. there seem "early-in-early-out" eieo pattern (run heap perhaps?).
the question is: determines lock granting order and can relied on not starving unlucky thread?
update: this answer explains it. here pertinent quote (joe duffy's concurrent programming on windows):
because monitors use kernel objects internally, exhibit same roughly-fifo behavior os synchronization mechanisms exhibit (described in previous chapter). monitors unfair, if thread tries acquire lock before awakened waiting thread tries acquire lock, sneaky thread permitted acquire lock.
servy's answer of course correct. few additional details:
what determines lock granting order?
ultimately, operating system.
can relied on not starving unlucky thread?
starvation unlikely possible. if cannot abide small chance of starvation, you'll need more complicated lock.
i note locks "unfair" in can have 1 thread in lock, 8 threads waiting, thread in lock leaves, , tenth thread not waiting @ asks lock , gets it, "cutting line". joe gives interesting analysis of why windows uses "unfair" lock allocation strategies here, if subject interests you:
http://www.bluebytesoftware.com/blog/permalink,guid,e40c2675-43a3-410f-8f85-616ef7b031aa.aspx
Comments
Post a Comment