1

I have
int counter
And have increment it in multithread by
Interlocked.Increment(ref counter);
Is thread safe reading it in other thread (while others still incrementing it) like this:
int localSaved = counter;
or
int localSaved = Interlocked.CompareExchange(ref counter, 0, 0);?
Not really know how 'Interlocked.CompareExchange' work but found it in google.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
KeyKiller
  • 65
  • 4
  • 2
    Some good answers on the "duplicate," but when you read them, pay attention to the question that some of the "answers" ask back: What does "thread-safe" even mean in this context? Suppose your "reader" thread copies the "correct" value of `counter` into `localSaved`. What then? By the time your reader thread does anything with `localSaved`, the `counter` could already have changed, maybe more than once. If that's not a problem for you, then your idea (if not your actual code) is "thread-safe." But it might be a problem for somebody else, and for them the same exact idea is not "thread-safe." – Solomon Slow Nov 05 '22 at 14:27

0 Answers0