当前位置: C语言 -- 标准库 -- <stdatomic.h> -- atomic_exchange_explicit

atomic_exchange_explicit函数


概要:
#include <stdatomic.h>
C atomic_exchange_explicit(volatile A *object, 
      C desired, memory_order order);

描述:

该泛型函数使用参数desired的值替换参数object指向的原子对象值,并返回该操作生效前原子对象的值。该操作是原子的读-修改-写操作。内存会受参数order值影响。当参数order值为memory_order_seq_cst时,atomic_exchange_explicit函数与atomic_exchange函数具有相同的语义。


参数:
volatile A *object

指向原子类型对象的指针。

C desired

对应的非原子类型对象。

memory_order order

枚举常量,显式地指定内存顺序。


返回值:

函数返回函数调用生效前参数object指向的原子对象值。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
/*函数atomic_exchange_explicit范例*/

#ifdef __STDC_NO_ATOMICS__
#error "Implementation does not support atomic types."
#endif

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

#define THREAD 2

atomic_int aNumber;

/*线程一中执行的函数。*/
int funcOne(void *arg)
{
    atomic_exchange_explicit(&aNumber, 25, memory_order_release);
    
    thrd_exit(0);
}

/*线程二中执行的函数。*/
int funcTwo(void *arg)
{
    int i;
    while(!(i = atomic_load_explicit(&aNumber, memory_order_acquire)))
        ;
    printf("After exchange aNumber is %d.\n", i);
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId[THREAD];
    atomic_init(&aNumber, 0);

    if(thrd_create(&threadId[0], funcOne, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }
    
    if(thrd_create(&threadId[1], funcTwo, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }

    thrd_join(threadId[0], NULL);
    thrd_join(threadId[1], NULL);
    
    return 0;
}


输出:

After exchange aNumber is 25.

注:使用Pelles C编译。


相关内容:
atomic_store_explicit 替换原子对象值的函数。
atomic_load_explicit 读取原子对象值的函数。
atomic_exchange 读取并替换原子对象值的函数。
atomic_compare_exchange_strong_explicit 根据比较结果,更新值的函数。
atomic_compare_exchange_weak_explicit 根据比较结果,更新值的函数。