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

atomic_store函数


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

描述:

该泛型函数使用参数desired的值替换参数object指向原子对象的值,该操作是原子写操作。


参数:
volatile A *object

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

C desired

对应的非原子类型对象。


返回值:

无。


范例:
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_store范例*/

#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_explicit 替换原子对象值的函数。
atomic_load 读取原子对象值的函数。
atomic_exchange 读取并替换原子对象值的函数。
atomic_compare_exchange_strong 根据比较结果,更新值的函数。
atomic_compare_exchange_weak 根据比较结果,更新值的函数。