当前位置:
C语言 --
标准库 --
<stdatomic.h> -- atomic_flag_test_and_set
atomic_flag_test_and_set函数
概要:
#include <stdatomic.h>
bool atomic_flag_test_and_set(
volatile atomic_flag *object);
描述:
该函数原子地将参数object指向的对象设置为设置状态(set state),并返回与前一个状态对应的值。该操作是原子的读-修改-写操作。
ISO/IEC 9899标准未指定atomic_flag_test_and_set是宏还是具有外部链接的标识符。如果为访问实际函数而抑制宏定义,或者程序定义了与atomic_flag_test_and_set同名的外部标识符,其行为是未定义的。
参数:
volatile atomic_flag *object
指向atomic_flag类型对象的指针。
返回值:
该函数返回函数调用生效前与atomic_flag类型对象的状态相对应的值。返回值true对应的是设置状态(set state);返回值false对应的是清除状态(clear state)。
范例:
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_test_and_set范例*/
#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))
thrd_yield();
++number;
/*释放lock。*/
atomic_flag_clear(&lock);
}
return 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
相关内容:
主要参考资料:
1、ISO/IEC 9899:2024
2、ISO/IEC 9899:2018