简体   繁体   English

为c,openmp实现CAS

[英]Implementation of CAS for c, openmp

I'm trying to implement the compare and swap operation so that my threads know whether or not to enter a particular region based on a value u_parent . 我正在尝试实现比较和交换操作,以便我的线程知道是否基于值u_parent进入特定区域。 I just want to know if this is the correct way to implement it and if I am going wrong somewhere. 我只想知道这是否是实现它的正确方法,以及我是否在某处出错。

int *u_parent;
u_parent = &graph->parents[u]; 

if (*u_parent < 0) { 
    // This region should only be entered by each thread
    // if the value of u_parent is < -1.   

    graph->parents[u] = v;
    // ^-- If region is entered, this value is modified
    // by some variable v

    //Swap:
    u_parent = &graph->parents[u];

    DO_SOMETHING();
}

Is this implementation correct because I am still seeing other threads enter this region after the CAS operation? 该实现是否正确,因为在CAS操作之后我仍然看到其他线程进入该区域?

I'm trying to implement the compare and swap operation 我正在尝试实现比较和交换操作

You cannot implement that in C. Such an operation has to be atomic to be meaningfully usable for synchronization purposes between threads. 不能在C中实现该操作。此类操作必须是原子性的 ,才能有意义地用于线程之间的同步。 Be aware of sequence points and memory models . 注意序列点内存模型

Some compilers provide a builtin for that. 一些编译器为此提供了一个内置函数。 (See also this question). (另请参阅问题)。 Recent GCC provide atomic builtins including __atomic_compare_exchange which generally gets compiled into a single machine code instruction. 最近的GCC提供了原子内建 __atomic_compare_exchange ,包括__atomic_compare_exchange ,它们通常被编译成单个机器代码指令。 Read the wikipage on compare-and-swap 阅读关于比较和交换的维基页面

On Linux, be also aware of futex(7) . 在Linux上,还要注意futex(7) With machine instructions like CMPXCHG they are the building blocks of many pthreads(7) operations (so require some assembler code). 使用诸如CMPXCHG之类的机器指令,它们是许多pthreads(7)操作的构建块(因此需要一些汇编代码)。 Read also a good pthread tutorial . 另请阅读优秀的pthread教程 The C11 standard (read n1570 ) provides <stdatomic.h> (in practice, the standard atomic operations are builtin to the compiler, or uses existing builtins). C11标准(读取n1570 )提供了<stdatomic.h> (实际上,标准原子操作内置于编译器中,或使用现有的内置物)。

Study also the source code of existing free software C standard libraries, eg GNU glibc or musl-libc . 还研究现有的自由软件 C标准库的源代码,例如GNU glibcmusl-libc You'll see that many synchronization primitives are built above futexes, assembler code, and/or compiler builtins. 您会看到许多同步原语是在futex,汇编代码和/或编译器内置文件之上构建的。

Also, OpenMP (when it is implemented by the compiler) is changing the behavior of the compiler (and of course of the generated executable). 另外, OpenMP (由编译器实现时)正在改变编译器(当然还有生成的可执行文件)的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM