问题描述
Windows API提供 InterlockedExchange
,它以原子方式在内存中设置一个值。只使用GCC内在函数,我想创建一个等价的函数。设置该值然后调用内存屏障就足够了(请参阅下面的代码)?
模板< typename T>
T InterlockedExchange(volatile T& _data,T _value)
{
const T oldValue = _data;
_data = _value;
__sync_synchronize();
返回oldValue;
$ / code>
谢谢。
:建议的片段是 NOT 正确的解决方案,因为它显然不是原子的(但是,我必须至少尝试一下) 使用
__ sync_lock_test_and_set
,而不是 __ sync_synchronize
。 这个功能完全一样作为InterlockedExchange。
类似这样(未经测试的代码!):
template< typename T> T InterlockedExchange(T& data,T& new_val)
{
return __sync_lock_test_and_set(& data,new_val);
}
编辑:
Oi,我读错了,你想InterlockedExchange,而不是InterlockedCompareExchange ...所以这是 __ sync_lock_test_and_set
(该名称是一个误导性的英特尔nomer,但它正是你想要的)。
请参阅,底部的页面。
Windows API offers InterlockedExchange
, which sets a value in memory atomically. Using only GCC intrinsics, I’d like to create an equivalent of that function. Would setting the value and then calling a memory barrier be sufficient (see the code below) ?
template <typename T>
T InterlockedExchange(volatile T& _data, T _value)
{
const T oldValue = _data;
_data = _value;
__sync_synchronize();
return oldValue;
}
Thank you.
EDIT: The proposed snippet is NOT a correct solution to the problem, as it is clearly not atomic (but, well, I had to give a try at least).
Use __sync_lock_test_and_set
, not __sync_synchronize
.
This has exactly the same function as InterlockedExchange.
Something like this (untested code!):
template<typename T> T InterlockedExchange(T& data, T& new_val)
{
return __sync_lock_test_and_set(&data, new_val);
}
EDIT:
Oi, I read wrong, you wanted InterlockedExchange, not InterlockedCompareExchange ... so that is __sync_lock_test_and_set
(the name is a misleading Intel-nomer, but it's exactly what you want).
See here, bottom of the page.
这篇关于移植InterlockedExchange,仅使用GCC内在函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!