简单的无锁秒表

时间:2016-06-13 21:46:10

标签: c# stopwatch atomicity lockless

根据MSDN,Stopwatch类实例方法对于多线程访问并不安全。这也可以通过检查个别方法来确认。

但是,由于我在代码中的几个地方只需要简单的“经过时间”的定时器,我想知道它是否仍然可以无锁地完成,使用类似的东西:

public class ElapsedTimer : IElapsedTimer
{
    /// Shared (static) stopwatch instance.
    static readonly Stopwatch _stopwatch = Stopwatch.StartNew();

    /// Stopwatch offset captured at last call to Reset
    long _lastResetTime;

    /// Each instance is immediately reset when created
    public ElapsedTimer()
    { 
        Reset();
    }

    /// Resets this instance.
    public void Reset()
    {
        Interlocked.Exchange(ref _lastResetTime, _stopwatch.ElapsedMilliseconds);
    }

    /// Seconds elapsed since last reset.
    public double SecondsElapsed
    {
        get
        {
             var resetTime = Interlocked.Read(ref _lastResetTime);
             return (_stopwatch.ElapsedMilliseconds - resetTime) / 1000.0;
        }
    }
}

由于_stopwatch.ElapsedMilliseconds基本上是对QueryPerformanceCounter的调用,我假设从多个线程调用是安全的?与常规Stopwatch的区别在于此类基本上一直在运行,所以我不需要保持任何附加状态(“运行”或“停止”),就像Stopwatch那样

(适用更新)

在@Scott在下面的答案中提出建议之后,我意识到Stopwatch提供了一个简单的静态GetTimestamp方法,它返回原始QueryPerformanceCounter刻度。换句话说,可以将代码修改为此,这是线程安全的:

public class ElapsedTimer : IElapsedTimer
{
    static double Frequency = (double)Stopwatch.Frequency;

    /// Stopwatch offset for last reset
    long _lastResetTime;

    public ElapsedTimer()
    { 
        Reset();
    }

    /// Resets this instance.
    public void Reset()
    {
        // must keep in mind that GetTimestamp ticks are NOT DateTime ticks
        // (i.e. they must be divided by Stopwatch.Frequency to get seconds,
        // and Stopwatch.Frequency is hw dependent)
        Interlocked.Exchange(ref _lastResetTime, Stopwatch.GetTimestamp());
    }

    /// Seconds elapsed since last reset
    public double SecondsElapsed
    {
        get
        { 
            var resetTime = Interlocked.Read(ref _lastResetTime);
            return (Stopwatch.GetTimestamp() - resetTime) / Frequency; 
        }
    }
}

澄清这段代码的想法是:

  1. 有一种简单快捷的方法来检查自某个操作/事件以来是否已经过了一段时间,
  2. 如果从多个线程调用,
  3. 方法不应该破坏状态,
  4. 必须对OS时钟更改(用户更改,NTP同步,时区等)不敏感。
  5. 我会使用它类似于:

    private readonly ElapsedTimer _lastCommandReceiveTime = new ElapsedTimer();
    
    // can be invoked by multiple threads (usually threadpool)
    void Port_CommandReceived(Cmd command)
    {
        _lastCommandReceiveTime.Reset();
    }
    
    // also can be run from multiple threads
    void DoStuff()
    {
        if (_lastCommandReceiveTime.SecondsElapsed > 10)
        {
            // must do something
        }
    }
    

2 个答案:

答案 0 :(得分:1)

我建议的唯一更改是使用Interlocked.Exchange(ref _lastResetTime, _stopwatch.ElapsedTicks);而不是毫秒,因为如果您处于高性能模式,则可以从QueryPerformanceCounter获得亚毫秒的结果。

答案 1 :(得分:0)

我建议创建Stopwatch的多个实例,并且只在同一个帖子上读取它。

我不知道您的异步代码是什么样的,但在psuedo代码中,我会这样做:

Stopwatch watch = Stopwatch.Startnew();
DoAsyncWork((err, result) =>
{
  Console.WriteLine("Time Elapsed:" + (watch.ElapsedMilliseconds / 1000.0));
  // process results...
});

或者:

public DoAsyncWork(callback) // called asynchronously
{
  Stopwatch watch = Stopwatch.Startnew();
  // do work
  var time = watch.ElapsedMilliseconds / 1000.0;
  callback(null, new { time: time });
}

第一个示例假设DoAsyncWork工作在另一个线程中完成工作,然后在完成时调用回调,然后编组回调用者线程。

第二个例子假设调用者正在处理线程,这个函数自己完成所有的计时,并将结果传回给调用者。