Skip to main content
 首页 » 编程设计

c#之线程间基于回合的同步

2024年02月13日20cloudgamer

我正在尝试找到一种方法来同步具有以下条件的多个线程:

  • 线程有两种类型:
    1. 单个“循环”线程执行无限循环以进行循环计算
    2. 多个短命线程不是由主线程启动的
  • 循环线程在每次循环/循环迭代之间有一个休眠持续时间
  • 允许其他线程在循环线程的周期间休眠期间执行:
    • 任何其他试图在事件周期内执行的线程都应该被阻止
    • 循环线程将等待所有其他已经在执行的线程完成

这是我想做的事情的一个基本示例:

// Somewhere in the code: 
ManualResetEvent manualResetEvent = new ManualResetEvent(true); // Allows external call 
CountdownEvent countdownEvent = new CountdownEvent(1); // Can't AddCount a CountdownEvent with CurrentCount = 0 
 
void ExternallyCalled() 
{ 
    manualResetEvent.WaitOne(); // Wait until CyclicCalculations is having its beauty sleep 
 
    countdownEvent.AddCount(); // Notify CyclicCalculations that it should wait for this method call to finish before starting the next cycle 
 
    Thread.Sleep(1000); // TODO: Replace with actual method logic 
 
    countdownEvent.Signal(); // Notify CyclicCalculations that this call is finished 
} 
 
void CyclicCalculations() 
{ 
    while (!stopCyclicCalculations) 
    { 
        manualResetEvent.Reset(); // Block all incoming calls to ExternallyCalled from this point forward 
 
        countdownEvent.Signal(); // Dirty workaround for the issue with AddCount and CurrentCount = 0 
        countdownEvent.Wait(); // Wait until all of the already executing calls to ExternallyCalled are finished 
 
        countdownEvent.Reset(); // Reset the CountdownEvent for next cycle. 
 
        Thread.Sleep(2000); // TODO: Replace with actual method logic 
 
        manualResetEvent.Set(); // Unblock all threads executing ExternallyCalled 
 
        Thread.Sleep(1000); // Inter-cycles delay 
    } 
} 

显然,这是行不通的。不能保证在 manualResetEvent.WaitOne(); 和 countdownEvent.AddCount(); 之间不会有任何线程执行 ExternallyCalled > 在 CountdownEvent 释放主线程时。

我想不出一种简单的方法来做我想做的事情,经过长时间的搜索后我发现的几乎所有东西都与生产者/消费者同步有关,我不能在这里应用。

编辑:解决方案

根据接受的答案,这是如何做我想做的事情的要点:

// Somewhere in the code: 
ReaderWriterLockSlim readerWriterLockSlim = new ReaderWriterLockSlim(); 
 
void ExternallyCalled() 
{ 
    readerWriterLockSlim.EnterReadLock(); 
 
    Thread.Sleep(1000); // TODO: Replace with actual method logic 
 
    readerWriterLockSlim.ExitReadLock(); 
} 
 
void CyclicCalculations() 
{ 
    while (!stopCyclicCalculations) 
    { 
        readerWriterLockSlim.EnterWriteLock(); 
 
        Thread.Sleep(2000); // TODO: Replace with actual method logic 
 
        readerWriterLockSlim.ExitWriteLock(); 
 
        Thread.Sleep(1000); // Inter-cycles delay 
    } 
} 

请您参考如下方法:

看起来你需要一个 ReaderWriterLockSlim .你的循环线程是“作者”,其他线程是“读者”。