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

atomic_flag类型


描述:

该类型是表示锁无关的、原始原子标志(primitive atomic flag)的结构类型。该类型对象存在两种状态:设置状态(set)和清除状态(clear)。该类型提供了经典的测试和设置功能;所有对该类型对象的操作都应该是锁无关的。


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

#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_INIT 初始化atomic_flag类型对象的宏。
atomic_flag_test_and_set atomic_flag类型对象设置为设置状态的函数。
atomic_flag_clear atomic_flag类型对象设置为清除状态的函数。