Monday 15 August 2011

c# - Semaphore: understanding initial and maximum number of requests -



c# - Semaphore: understanding initial and maximum number of requests -

i'm learning c# semaphore , don't understand 1 point. can initialize semaphore this:

var semaphore = new semaphore(4, 6);

there such explanation in many places:

if want reserve slots calling thread, can making first parameter smaller second.

does mean main thread can utilize remaining 2 resource slots? mean if write this:

var semaphore = new semaphore(0, 6);

only main thread can utilize 6 slots?

unlike lock (monitor) , mutex, semaphore has no “owner” — it’s thread-agnostic. thread can phone call release on semaphore, whereas mutex , lock, thread obtained lock can release it.

initial value can used initiate number of requests semaphore can granted concurrently. sets available concurrency level related sempahore.

while maximum count sets maximum number of requests semaphore can granted concurrently. sets maximum potential concurrency related semaphore.

you can't increment counter currentcount greater maximum count set in initialization.

following sample shows how semaphores thread agnostic:

private static semaphore semaphore = new semaphore(3, 6); private static void main(string[] args) { //semaphore.release(); //openning slot concurreny semaphore.waitone(); console.writeline("main0"); new thread(() => { semaphore.waitone(); console.writeline("thread0"); semaphore.waitone(); console.writeline("thread1"); thread.sleep(3000); console.writeline("uncomment release line create main1 in"); }).start(); thread.sleep(1000); semaphore.waitone(); console.writeline("main1"); console.readkey(); }

for more info have @ http://www.albahari.com/threading/part2.aspx#_semaphore

c# multithreading semaphore

No comments:

Post a Comment