问题描述
http://msdn.microsoft.com/zh-我们/library/system.threading.semaphoreslim.aspx
要创建信号灯,我需要提供一个初始计数和最大计数.MSDN指出,初始计数为-
To create a semaphore, I need to provide an initial count and maximum count. MSDN states that an initial count is -
虽然声明最大数量为
我可以理解,最大数量是可以同时访问资源的最大线程数.但是,初始计数的用途是什么?
I can understand that the maximum count is the maximum number of threads that can access a resource concurrently. But, what is the use of initial count?
如果创建的信号量的初始计数为0,最大计数为2,则我的线程池线程都无法访问该资源.如果我将初始计数设置为1,将最大计数设置为2,则只有线程池线程可以访问该资源.仅当我将初始计数和最大计数都设置为2时,两个线程才能够同时访问资源.所以,我真的对初始计数的重要性感到困惑吗?
If I create a semaphore with an initial count of 0 and a maximum count of 2, none of my threadpool threads are able to access the resource. If I set the initial count as 1 and maximum count as 2 then only thread pool thread can access the resource. It is only when I set both initial count and maximum count as 2, 2 threads are able to access the resource concurrently. So, I am really confused about the significance of initial count?
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 2); //all threadpool threads wait
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 2);//only one thread has access to the resource at a time
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2, 2);//two threadpool threads can access the resource concurrently
推荐答案
是的,当初始数字设置为0时,在增加"CurrentCount"属性时,所有线程都将等待.您可以使用Release()或Release(Int32).
Yes, when the initial number sets to 0 - all threads will be waiting while you increment the "CurrentCount" property. You can do it with Release() or Release(Int32).
Release(...)-将增加信号量计数器
Release(...) - will increment the semaphore counter
等待(...)-将其递减
Wait(...) - will decrement it
您不能将计数器("CurrentCount"属性)的增量增加到大于初始化时设置的最大计数.
You can't increment the counter ("CurrentCount" property) greater than maximum count which you set in initialization.
例如:
SemaphoreSlim^ s = gcnew SemaphoreSlim(0,2); //s->CurrentCount = 0
s->Release(2); //s->CurrentCount = 2
...
s->Wait(); //Ok. s->CurrentCount = 1
...
s->Wait(); //Ok. s->CurrentCount = 0
...
s->Wait(); //Will be blocked until any of the threads calls Release()
这篇关于信号量-初始计数有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!