c# - 最简单的并发模式

标签 c# concurrency semaphore parallel-processing

请您帮我提醒一下最简单的并行编程技术之一。

如何在 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

它不是互斥体,因为没有临界区,或者更确切地说,你可以说有一个无限的临界区。那么它是什么?

最佳答案

关于“如何”...好吧,你可以使用 Semaphore , Mutex或重置事件( ManualResetEventAutoResetEvent ),但我个人使用 Monitor

object sync = new object();

线程 1:

lock(sync) { // blocks until it successfully takes (re-entrant) lock on sync
    // here: launch thread 2, to ensure thread 1 has the lock first
    Monitor.Wait(sync); // releases lock(s) and waits for pulse,
                        // then retakes locks(s) when free
} // releases lock (or decrement by 1)

线程 2:

lock(sync) { // blocks until it successfully takes (re-entrant) lock on sync
    Monitor.Pulse(sync); // moves a waiting thread into the ready-queue
                         // (but the awoken thread still can't continue until
                         // it gets the lock itself - and we still hold it)
} // releases lock (or decrement by 1)

关于c# - 最简单的并发模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308900/

相关文章:

C++ - 进程间共享的互斥量

c - 在 C 中使用信号量处理套接字

c# - 如何以编程方式判断我是否在 Medium Trust 下运行?

sql - 在 PostgreSQL 中处理竞争条件

javascript - Node js 中的信号量等效,变量在并发请求中被修改?

c# - 多个作者,一个读者,哪个集合

multithreading - 多个线程可以同时等待一个信号量

c# - 任何人都可以举一个很好的例子来说明泛型类的用途吗?

c# - Parallel.For() 会随着重复执行而变慢。我应该看什么?

c# - 无法在 C# 中导入 AzureAD 模块