移植InterlockedExchange,仅使用GCC内在函数 [英] Porting InterlockedExchange, using GCC intrinsics only

查看:973
本文介绍了移植InterlockedExchange,仅使用GCC内在函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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_val_compare_and_swap __ 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_val_compare_and_swap __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内在函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆