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

atomic_load函数


概要:
#include <stdatomic.h>
C atomic_load(const volatile A *object);

描述:

该泛型函数读取参数object指向的原子对象值,该操作是原子读操作。


参数:
const volatile A *object

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


返回值:

函数返回参数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 
/*函数atomic_load范例*/

#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>

atomic_int aNumber;

/*新线程中执行的函数。*/
int func(void *arg)
{
    atomic_store(&aNumber, 25);
    printf("aNumber: %d\n", atomic_load(&aNumber));
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId;
    atomic_init(&aNumber, 10);

    if(thrd_create(&threadId, func, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }

    thrd_join(threadId, NULL);
    
    return 0;
}


输出:

aNumber: 25

注:使用Pelles C编译。


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