最简单的并发模式
请您帮我提醒我最简单的并行编程技术之一。
我如何在 C# 中执行以下操作:
初始状态:
semaphore counter = 0
线程 1:
// Block until semaphore is signalled
semaphore.Wait(); // wait until semaphore counter is 1
线程 2:
// Allow thread 1 to run:
semaphore.Signal(); // increments from 0 to 1
它不是互斥锁,因为没有临界区,或者更确切地说,您可以说存在无限临界区。那么它是什么?
Please, would you help me in reminding me of one of the simplest parallel programming techniques.
How do I do the following in C#:
Initial state:
semaphore counter = 0
Thread 1:
// Block until semaphore is signalled
semaphore.Wait(); // wait until semaphore counter is 1
Thread 2:
// Allow thread 1 to run:
semaphore.Signal(); // increments from 0 to 1
It's not a mutex because there is no critical section, or rather you can say there is an infinite critical section. So what is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于“如何”...好吧,您可以使用 信号量< /a>、互斥体 或重置事件 (< a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx" rel="nofollow">ManualResetEvent,AutoResetEvent),但我个人使用
Monitor
来实现;线程 1:
线程 2:
Re "how"... well, you could use a Semaphore, Mutex or reset-event (ManualResetEvent, AutoResetEvent), but personally I use
Monitor
for that;thread 1:
thread 2:
你写的只是一个互斥锁;互斥体与值为 1 的信号量基本相同。并且有一个“临界区”——它是任一线程持有互斥体时执行的代码序列。
What you wrote is simply a mutex; a mutex is basically the same as a semaphore with value 1. And there is a 'critical section' - it's the code sequence which is executed while either thread holds the mutex.
信号量初始化为 1,可以被视为[读取:使用]作为互斥锁。
您描述的具体场景是信号量在两个线程之间使用信号系统。
第一个线程尝试锁定资源[获取信号量],但被阻塞[因为信号量已初始化为零],直到第二个线程向线程 1 发出信号,表明他可以输入代码的其余部分。
关于该主题的一篇优秀文章是:
http://geekswithblogs.net/shahed /archive/2006/06/09/81268.aspx
A semaphore initialized to 1, can be seen [read: used] as a mutex.
The specific scenario you are describing is a semaphore used a signaling system between two threads.
The first thread tries to lock the resourse [acquire the semaphore] but gets blocked [because the semaphore has been initialized to zero], until the second thread signal thread 1 that he can enter the remaining part of the code.
An excellent article on the topic is:
http://geekswithblogs.net/shahed/archive/2006/06/09/81268.aspx