简体   繁体   中英

Best thread-safe way to increment an integer up to 65535

I have a System.Timers.Timer that increments a counter every 3 seconds. Another thread may also set this variable to any value under some conditions.

Tried to use Interlocked.Increment but it does not have an overload for UInt16. The next thing in mind is lock , but I am not really sure how to make thread-safe access (read/write/increment) to this variable.

Edited: the code originally used an int, but changed to UInt16 as suggested

private volatile System.UInt16 mCounter = 0;
private readonly object mCounterLock = new object();
public System.UInt16 Counter {
  get {
    lock (mCounterLock) {
      return mCounter;
    }
  }
  set {
    lock (mCounterLock) {
      mCounter = value;
    }
  }
}
private System.Timers.Timer mCounterTimer;

void mCounter_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
  lock (mCounterLock) {
    Counter++;
  }
}

使用Interlocked.CompareExchangeInterlocked.Increment的组合,其中如果值达到65535,则指定0

Just change your Int32 value to Int16 if you only need 2 bytes. Since Shai removed his answer here's some code

UInt16 myval = 0;
Object myvalLock = new Object();
....
lock (myvalLock) { myval++; }

我只需使用带有Interlocked.IncrementUInt32 ,并在每次读取访问后将其UInt16UInt16

volatile int iNum = 0;
...


iActual = iNum;
do
{
   iExpected = iActual;
   iNext = (iExpected+1) & 0xFFFF;
   iActual = Interlocked.CompareExchange (ref iNum, iNext, iExpected);
} while (iExpected != iActual);
return iNext;

This makes the increment thread safe vs. other increments. But you mention also 'read', 'write' and 'reset' and is impossible to tell, in context, if those operations are safe and even if the increment is dafe vs. said 'write' and specially 'reset' operations. Normally for such type of shared counters the only operation allowed is to increment it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM