|
InterLocked函数似乎没有停等的功能,我写了下面函数来实现如果共享产生竞争,则进入超时模式来等待重新访问共享数据
void WriteLock()
{
if( InterLockedCompareExchange(count,-1,0) != -1 )
{
//Lock request false, access timeout mode and continue to request..
int i=3;
for( i;i>0;i-- )
{
Sleep(0);
if( InterLockedCompareExchange(count,-1,0) == -1 )
{
break;
}
}
}
}
void WriteUnLock()
{
if( InterLockedCompareExchange(count,0,-1) != 0 )
{
//Unlock request false, access timeout mode and continue to request..
int i=3;
for( i;i>0;i-- )
{
Sleep(0);
if( InterLockedCompareExchange(count,0,-1) == 0 )
{
break;
}
}
//timeout and give up
}
}
main()
{
WriteLock();
DataCopy();
WriteUnLock();
}
以这样的方式来做,不知是否可行?? |
|