目前我正忙于摆弄 CAS 操作和无锁/无等待算法,为了我自己的理智,我决定实现一个模板来为我处理所有的转换:
VC6:
template <typename T> static inline T CAS(volatile T* pDest, T pCompare, T pValue)
{
//static_assert(sizeof(T) != sizeof(PVOID),"CAS requires PVOID sized operands");
return reinterpret_cast<T>(InterlockedCompareExchange(reinterpret_cast<PVOID*>(pDest),reinterpret_cast<PVOID>(pValue),reinterpret_cast<PVOID>(pCompare)));
}
海湾合作委员会 4.4.1:
template <typename T> static inline T CAS(volatile T* pDest, T pCompare, T pValue)
{
static_assert(sizeof(T) != sizeof(long),"CAS32 requires long sized operands");
return reinterpret_cast<T>(InterlockedCompareExchangePointer(reinterpret_cast<volatile long*>(pDest),reinterpret_cast<long>(pValue),reinterpret_cast<long>(pCompare)));
}
但是,使用一些简单的测试代码,我无法让它在volatile
目的地上工作,这是防止重新排序所必需的。
测试代码:
volatile int* p;
int i = 2;
int* pi = &i;
CAS(&p,NULL,pi);
在 VC6 下我得到这个错误:
error C2782: 'T __cdecl CAS(volatile T *,T,T)' : template parameter 'T' is ambiguous
could be 'int'
or 'volatile int *'
和 GCC 吐出这个:
error: no matching function for call to 'CAS(volatile int**, NULL, int*&)'
volatile
是否有可能为 CAS ops 获得一个模板,当目标是或我被宏卡住时不会中断?