我有一个 Windows 7 驱动程序,我想在其中同步对变量的访问。我可以使用 InterlockedExchange 吗?
我目前对 InterlockedExchange 的理解是,InterlockedExchange 是通过编译器内部函数完成的。这意味着读取(InterlockedExchange 返回旧值)和写入在一个时钟周期内完成。仅当始终通过互锁函数访问变量时,互锁函数才是原子的。
但是在这种情况下会发生什么:
CPU1: InterlockedExchange(&Adapter->StatusVariable, 5);
CPU2: InterlockedExchange(&Adapter->StatusVariable, 3);
StatusVariable 在两个 CPU 内核上以相同的时钟周期写入。该函数是否注意到变量被访问并将写入推迟到不同的时钟周期?还是 undefined variable 在写入后具有哪个值?是不是变量也有可能是垃圾?
编辑:我在 x86 或 x64 上。
最佳答案
InterlockedExchange 生成具有隐式内存屏障的 xchg 指令。
Intel Instruction set reference是你的 friend :) 有关锁如何工作的更多信息,请参阅第 8 章。
来自 XCHG 指令:
The exchange instructions swap the contents of one or more operands and, in some cases, perform additional operations such as asserting the LOCK signal or modifying flags in the EFLAGS register.
The XCHG (exchange) instruction swaps the contents of two operands. This instruction takes the place of three MOV instructions and does not require a temporary location to save the contents of one operand location while the other is being loaded. When a memory operand is used with the XCHG instruction, the processor’s LOCK signal is automatically asserted. This instruction is thus useful for implementing semaphores or similar data structures for process synchronization. See “Bus Locking” in Chapter 8, “Multiple-Processor Management,”of the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A, for more information on bus locking.
如果您对引用文献有任何疑问,请直接提问。
关于windows - 两个 CPU 内核上的 InterlockedExchange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18076416/