windows - 两个 CPU 内核上的 InterlockedExchange

标签 windows kernel interlocked

我有一个 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/

相关文章:

windows - 如何在windows上唯一标识一个进程?

php - 使用 PHP 的 proc_open + bypass_shell 在后台运行可执行文件并检索正确的 PID?

windows - 如何从 Windows 应用程序访问 DDC/CI 显示相关设备?

linux - QEMU源码中如何添加新设备?

linux - 在来自两个不同进程的相同文件描述符上调用 ioctl

c# - 由多个线程读取/写入的字段,Interlocked 与 volatile

c# - 在多线程应用程序中同步属性值的正确方法

windows - 如何在 Windows 上将 ssh 准确添加到 PATH?

c - linux内核宏如何用作函数?

.net - lock()在这里有意义吗?