一般进行多线程编程,进行同步时经常要用到同步内核对象event/mutex/semaphore等,但是内核对象的操作需要陷入到内核中,比较耗费cpu时间。
所以,当使用数组、链表等数据结构实现大量数据添加删除时,比如实现生产消费者模式时,用event等内核对象就比较耗费cpu。系统提供了一组InterLockedXXX原子操作API,我们可以利用这些函数实现锁操作。
1. 使用InterlockedExchange 实现
MSDN 定义
The InterlockedExchange routine sets aninteger variable to a given value as an atomic operation.
LONG
InterlockedExchange(
IN OUT PLONG Target,
IN LONG Value
);
Parameters
Target
Pointerto a variable to be set to the supplied Value as an atomic operation.
Valu