1

我试图从不同线程原子地写入2d数组(float ** W)。然而CAS总是给人这样的错误:不兼容的类型__sync_bool_compare_and_swap在2D阵列上比较和交换

c = __sync_bool_compare_and_swap(&W[uu][i], a, b);

当我写atomcially为一维数组它工作正常,像往常一样的参数1。

关于如何使这项工作的任何想法?我可以尝试在每个线程中创建1d数组,然后在屏障后更新这个2d数组,但这会占用太多内存。我正在使用Ubuntu/Linux。

谢谢。

+1

我不认为CAS函数支持浮点。无论是2D还是1D阵列都无关紧要,因为您只能将一个元素传递给该函数。 – interjay

+0

其实它支持浮动,我试着浮动*数组,它的工作。 – masab

+0

对不起,我不相信你。该函数不知道你传入的是一维或二维数组的一部分。 – interjay

回答

4
main() { 
    int* W = malloc(10); 
    int uu = 1, i = 3; 
    __sync_val_compare_and_swap(&W[uu], 1, 2); 
} 

编译罚款,但是:

main() { 
    float* W = malloc(10); 
    int uu = 1, i = 3; 
    __sync_val_compare_and_swap(&W[uu], 1.0f, 2.0f); 
} 

不编译给我你写的完全一样的消息。这表明浮动不支持:

The definition given in the Intel documentation allows only for the use of the types int, long, long long as well as their unsigned counterparts. GCC will allow any integral scalar or pointer type that is 1, 2, 4 or 8 bytes in length.

它看起来像这证实了这一点。

如果你不使用安腾那么也许

The four non-arithmetic functions (load, store, exchange, and compare_exchange) all have a generic version as well. This generic version works on any data type.

您可以使用__atomic_compare_exchange*,因为这些应该在任何类型根据文档工作。尽管如此,我还没有尝试过。

编辑:

main() { 
    float* W = malloc(10); 
    float target; 
    float val = 5.0f; 
    __atomic_exchange(&W[4], &val, &target, __ATOMIC_RELAXED); 
} 

^- 这至少编译。