You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用Interlocked.Add()?对其多线程加法安全性的困惑

Why Isn't Interlocked.Add() Behaving as Expected for Multi-Threaded Addition?

I totally get your frustration here—docs say Interlocked methods prevent context-switching bugs when updating shared variables, and there's explicit confirmation they're concurrently safe across any number of cores/CPUs. So when Interlocked.Add() doesn't seem to work as intended for multi-threaded addition, it's confusing. Let's break down the most common reasons this happens:

  • You're ignoring the return value or reading the shared variable directly
    Interlocked.Add() atomically updates the variable and returns the new updated value. If you skip using this return value and instead read the shared variable directly later (like int current = mySharedVar;), you might get a stale value due to compiler/CPU caching. Even though Interlocked operations enforce memory barriers, direct reads without proper synchronization can hit visibility edge cases. Always rely on the return value for the most up-to-date state, or use Volatile.Read() if you need to read the variable outside an Interlocked operation.

  • Non-atomic modifications exist elsewhere in your code
    Interlocked.Add() only guarantees atomicity for operations that use it. If any thread modifies the shared variable with a regular assignment (like mySharedVar += 1;) instead of Interlocked.Add(), you break the atomicity. Those non-Interlocked operations can interfere with atomic updates, leading to lost increments or inconsistent values. Double-check all code paths touching the variable—every modification needs to use Interlocked methods.

  • Your logical operation isn't fully atomic
    Interlocked.Add() makes the single addition atomic, but if your logic depends on a sequence of actions (like checking the variable's value before adding, or using the value for another calculation right after), the entire sequence isn't atomic. For example:

    // This is NOT atomic! The check and add are separate operations
    if (mySharedVar < 100)
    {
        Interlocked.Add(ref mySharedVar, 1);
    }
    

    Between the if check and Interlocked.Add(), another thread could modify the variable, leading to incorrect behavior. In cases like this, you need a full lock (like the lock statement) to make the entire sequence atomic.

  • You're using an unsupported type or wrong overload
    Interlocked.Add() only works with specific value types: int, long, uint, ulong (depending on your framework). If you're trying to use it with a custom type, floating-point number, or reference type, it won't work as intended. Double-check you're using the correct overload for your variable's type.

内容的提问来源于stack exchange,提问作者user3230660

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:49:17