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

ATOMIC_FLAG_INIT宏


概要:

#define ATOMIC_FLAG_INIT  value //value值由实现定义。


描述:

该宏将atomic_flag类型对象初始化为清除状态(clear state);未使用宏ATOMIC_FLAG_INIT显式初始化的atomic_flag类型对象处于不确定状态。


Pelles C编译器<stdatomic.h>头文件中,宏ATOMIC_FLAG_INIT定义如下:

    #define ATOMIC_FLAG_INIT	{ 0 }

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

#define THREADS 10

atomic_flag lock = ATOMIC_FLAG_INIT;
int number = 0;

/*新线程中执行的函数。*/
int func(void *arg)
{
    for(int i=0; i<10000; ++i)
    {
        /*获取lock。*/
        while(atomic_flag_test_and_set(&lock))
            ;
        ++number;
        
        /*释放lock。*/
        atomic_flag_clear(&lock);
    }

    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId[THREADS];
    
    for(int i=0; i<THREADS; ++i)
    {
        if(thrd_create(&threadId[i], func, NULL) != thrd_success)
        {
            perror("thrd_create error");
            exit(EXIT_FAILURE);
        }
    }

    for(int i=0; i<THREADS; ++i)
        thrd_join(threadId[i], NULL);

    printf("number: %d\n", number);

    return 0;
}


输出:

number: 100000

注:使用Pelles C编译。


相关内容:
atomic_flag 表示原子标志的结构类型。
atomic_flag_test_and_set atomic_flag类型对象设置为设置状态的函数。
atomic_flag_clear atomic_flag类型对象设置为清除状态的函数。