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

atomic_init函数


概要:
#include <stdatomic.h>
void atomic_init(volatile A *obj, C value);

描述:

该泛型函数将参数obj指向的原子对象初始化为参数value的值,同时还会初始化实现可能需要的与该原子对象相关的任何额外状态。如果该对象没有声明类型,函数调用后其有效类型(effective type)将是原子类型A。

ISO/IEC 9899标准未指定atomic_init是宏还是具有外部链接的标识符。如果为访问实际函数而抑制宏定义,或者程序定义了与atomic_init同名的外部标识符,其行为是未定义的。

尽管该函数用于初始化原子对象,但它并不能避免数据竞争;在初始化过程中并发(concurrent access)访问该对象,即使是通过原子操作(atomic operation)进行访问,也会构成数据竞争。

如果信号不是由于调用abort函数或者raise函数引发的,信号处理函数调用atomic_init泛型函数,其行为是未定义的。

从ISO/IEC 9899:2024标准起,atomic_init泛型函数是初始化动态内存中原子对象的唯一标准方法。


参数:
volatile A *obj

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

C value

对应的非原子类型值。


返回值:

无。


范例:
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 
/*函数atomic_init范例*/

#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, 15);
    printf("aNumber: %d\n", atomic_load(&aNumber));
    
    return 0;
}

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

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

    thrd_join(threadId, NULL);

    return 0;
}


输出:

aNumber: 15


相关内容:
ATOMIC_VAR_INIT 初始化原子变量的宏。


主要参考资料:

1、ISO/IEC 9899:2024

2、ISO/IEC 9899:2018