【发布时间】:2010-09-03 15:09:53
【问题描述】:
如果我们有:
__int32 some_var = 0;
调用InterlockedExchange、InterlockedIncrement 和其他需要LONG* 用于some_var 的联锁功能的最佳(如果有)方法是什么?
由于可以保证LONG 在任何Windows 上都是32 位的,因此通过(long*) some_var 可能是安全的。但是,在我看来,这很丑陋,我无法确认它是安全的。
注意,我无法将类型更改为long,因为它不可移植。我需要 32 位类型。
更新:对提供可移植原子操作的库的一些研究表明,没有人会担心强制转换。一些例子:
Apache Portable Runtime (APR):
typedef WINBASEAPI apr_uint32_t (WINAPI * apr_atomic_win32_ptr_val_fn)
(apr_uint32_t volatile *,
apr_uint32_t);
APR_DECLARE(apr_uint32_t) apr_atomic_add32(volatile apr_uint32_t *mem, apr_uint32_t val)
{
#if (defined(_M_IA64) || defined(_M_AMD64))
return InterlockedExchangeAdd(mem, val);
#elif defined(__MINGW32__)
return InterlockedExchangeAdd((long *)mem, val);
#else
return ((apr_atomic_win32_ptr_val_fn)InterlockedExchangeAdd)(mem, val);
#endif
}
AO_INLINE AO_t
AO_fetch_and_sub1_full (volatile AO_t *p)
{
return _InterlockedDecrement64((LONGLONG volatile *)p) + 1;
}
【问题讨论】:
标签: c++ c multithreading winapi interlocked