尝试创建 CAS 模板
目前我正忙着摆弄 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)));
}
GCC 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 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*&)'
是否可以获取 CAS 操作的模板,当目标为 易失性
时,该模板不会中断,或者我是否被宏困住了?
at the moment I'm busy fiddling with CAS operations and lock/wait-free algorithms, and for my own sanity I decided to implement a template to handling all the casting for me:
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)));
}
GCC 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)));
}
However, using some simple test code, I cannot get this to work on a volatile
destination, which is required to prevent reordering.
Test Code:
volatile int* p;
int i = 2;
int* pi = &i;
CAS(&p,NULL,pi);
Under VC6 I get this error:
error C2782: 'T __cdecl CAS(volatile T *,T,T)' : template parameter 'T' is ambiguous
could be 'int'
or 'volatile int *'
and GCC spits out this:
error: no matching function for call to 'CAS(volatile int**, NULL, int*&)'
is it possible to get a template for CAS ops that doesn't break when the destination is volatile
or am I stuck with a macro?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,如果我按如下方式调用 CAS 函数:
然后我会得到一个不同的错误:
这提供了更多关于出了什么问题的线索。
解决这个问题的一种方法是引入 typedef,如下所示:
OK if i call the CAS function as follows:
Then I get a different error:
This gives more of a clue as to what is going wrong.
One way to solve it would be to introduce a typedef as follows: