使用 InterlockedXXX实现自旋锁操作

一般进行多线程编程,进行同步时经常要用到同步内核对象event/mutex/semaphore等,但是内核对象的操作需要陷入到内核中,比较耗费cpu时间。

所以,当使用数组、链表等数据结构实现大量数据添加删除时,比如实现生产消费者模式时,用event等内核对象就比较耗费cpu。系统提供了一组InterLockedXXX原子操作API,我们可以利用这些函数实现锁操作。


1.   使用InterlockedExchange 实现

 

MSDN 定义

InterlockedExchange

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.

Value

Specifiesthe value to which the variable will be set.

Return Value

InterlockedExchange returnsthe value of the variable at Target when the call occurred.

该函数的返回值为Target的值,所以,我们可以利用返回值进行操作。

实现代码如下

 

class SpinLock
{
public:

	SpinLock() : m_lock( 0 ) {}
	~SpinLock(){}

	void Lock()
	{
		while( InterlockedExchange( &m_lock, 1 ) == 1 )
		{ 
			Sleep( 0 ); 
		}
	}

	void Unlock()
	{
		InterlockedExchange( &m_lock, 0 );
	}

private:
	volatile unsigned int m_lock;
};

解释:

当返回值等于1,说明已经m_lock已经被设置成1,所以已经被锁。调用sleep等待其他线程释放锁

当返回值等于0,说明没有其他线程上锁,而且当前线程将m_lock置为1,获得锁。

 

 

2.   使用InterLockedCompareExchange实现

 

InterlockedCompareExchange

The InterlockedCompareExchange routineperforms an atomic operation that compares the input value pointed to byDestinationwith the value ofComparand.

LONG
  InterlockedCompareExchange(
    IN OUT PLONG  
Destination,
    IN LONG  
Exchange,
    IN LONG  
Comparand
    );

Parameters

Destination

Pointerto the input value that is compared with the value of Comparand.

Exchange

Specifiesthe output value pointed to by Destination if the input value pointed tobyDestination equals the value ofComparand.

Comparand

Specifiesthe value that is compared with the input value pointed to by Destination.

Return Value

InterlockedCompareExchange returnsthe original value of *Destination.

该函数的返回值是调用成功前的值,所以实现逻辑如下

 

class SpinLockEx
{
public:

	SpinLockEx() : m_lock( 0 ) {}
	~SpinLockEx(){}

	void Lock()
	{
		while( InterlockedCompareExchange( &m_lock, 1 , 0) != 0 )
		{ 
			Sleep( 0 ); 
		}
	}

	void Unlock()
	{
		InterlockedExchange( &m_lock, 0 );
	}

private:
	volatile unsigned int m_lock;
};

 参考

 1. http://www.codeproject.com/Articles/184046/Spin-Lock-in-C

 2. 强烈推荐http://www.codeproject.com/Articles/14740/Fast-IPC-Communication-Using-Shared-Memory-and-Int ,通过InterlockCompareExchange与共享内存实现高速IPC,思想性能都很好。

你可能感兴趣的:(Lock,高性能,Interlocked)