c# - 信号量 - 初始计数有什么用?

标签 c# multithreading concurrency semaphore

http://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim.aspx

要创建信号量,我需要提供初始计数和最大计数。 MSDN 指出初始计数是 -

The initial number of requests for the semaphore that can be granted concurrently.

虽然它声明最大计数是

The maximum number of requests for the semaphore that can be granted concurrently.

我可以理解为maximum count是可以并发访问一个资源的最大线程数。但是,初始计数有什么用呢?

如果我创建一个初始计数为 0 且最大计数为 2 的信号量,则我的线程池线程都无法访问该资源。如果我将初始计数设置为 1,将最大计数设置为 2,则只有线程池线程可以访问该资源。只有当我将初始计数和最大计数都设置为 2 时,2 个线程才能同时访问资源。所以,我真的很困惑初始计数的意义?

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) 来实现。

Release(...) - 将增加信号量计数器

Wait(...) - 会递减它

您不能将计数器(“CurrentCount”属性)递增到大于您在初始化时设置的最大计数。

例如:

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()

关于c# - 信号量 - 初始计数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4706734/

相关文章:

c# - 确保类是线程安全的,只有属性(任何专门用于此的 .NET 4.0 技术?)

c# - 与 C# 和 C++ 相比,Python 中的并发支持

swift - iOS swift 操作队列

c# - .net framework 4.0 c# 中的文件压缩

c# - C#中的命名空间和子命名空间

c++ - fetch_sub 真的是原子的吗?

java - join 执行不完整

C# 代码契约(Contract) : Are postconditions on members accessible from other threads useless?

c# - 访问 sharepoint 搜索 REST API

Android - C++ for 循环与从 Java 线程调用的 OpenMP(减少)并行化导致段错误