这个锁+ ManualResetEvent使用线程安全吗?

时间:2019-06-13 15:09:55

标签: c# .net multithreading concurrency

这是一个基于this question的独立问题。回顾一下,假设我有两个操作计数的函数,以及一个定期触发的OnTimer函数。我的愿望是,如果/当调用OverwriteCount时,在执行计时器函数之前不能执行IncrementCount。

建议的解决方案是:

private int _myCount = 0;
private readonly object _sync = new object();
private ManualResetEventSlim mre = new ManualResetEventSlim(initialState: true);

void IncrementCount()
{
    mre.Wait(); // all threads wait until the event is signaled

    lock (_sync)
    {
        _myCount++;
    }
}

void OverwriteCount(int newValue)
{
    lock (_sync)
    {
        mre.Reset(); // unsignal the event, blocking threads
        _myCount = newValue;
    }
}

void OnTimer()
{
    lock (_sync)
    {
        Console.WriteLine(_myCount);
        mre.Set(); // signal the event
    }
}

ManualResetEventSlim尝试确保一旦OverwriteCount()解除事件的信号,对_myCount的任何修改都必须等到OnTimer()执行之后。

问题

  1. 说线程A输入IncrementCount()并传递事件的wait()-已经指示了ManualResetEvent的初始状态。
  2. 然后,
  3. 线程B启动并执行所有OverwriteCount()。
  4. 然后,
  5. 线程A通过获取锁并递增_myCount来继续。

这违反了我的目标,因为_myCount会在OnTimer运行之前调用OverwriteCount()之后更改。

被拒绝的选择:我可以将mre.Wait()移入lock(_sync)内,但这会带来死锁风险。如果线程A调用IncrementCount()并在等待时阻塞,则其他线程都无法获取该锁来释放它。

问题:我是否需要其他同步原语才能实现目标?或者,我是否对线程安全性有疑问?

1 个答案:

答案 0 :(得分:1)

我认为您只需使用标准的Monitor和一个附加标志就可以实现您的目标。

private readonly object _sync = new object();
private int _myCount = 0;
private bool _canIncrement = true;

void IncrementCount()
{
    lock (_sync)
    {
        // If the flag indicates we can't increment, unlock _sync and wait for a pulse.
        // Use a loop here to ensure that if Wait() returns following the PulseAll() below
        // (after re-acquiring the lock on _sync), but a call to OverwriteCount managed to
        // occur in-between, that we wait again.
        while (!_canIncrement)
        {
            Monitor.Wait(_sync);
        }

        _myCount++;
    }
}

void OverwriteCount(int newValue)
{
    lock (_sync)
    {
        _canIncrement = false;
        _myCount = newValue;
    }
}

void OnTimer()
{
    lock (_sync)
    {
        Console.WriteLine(_myCount);
        _canIncrement = true;
        // Ready any threads waiting on _sync in IncrementCount() above
        Monitor.PulseAll(_sync);
    }
}