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

ONCE_FLAG_INIT宏


概要:

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


描述:

该宏扩展为可用于初始化once_flag类型对象的值。


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

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

#define THREADS 3

once_flag flag = ONCE_FLAG_INIT;

/*只被执行一次的函数。*/
void performOneTime(void)
{
    puts("Perform one time.");
}

/*在新线程中执行的函数。*/
int threadFunc(void *arg)
{
    call_once((once_flag *)arg, performOneTime);
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId[THREADS];
    
    /*创建新线程。*/
    for(int i=0; i<THREADS; ++i)
    {
        if(thrd_create((threadId+i), threadFunc, &flag) != thrd_success)
        {
            perror("thrd_create");
            exit(EXIT_FAILURE);
        }
    }
    
    /*连接线程。*/
    for(int i=0; i<THREADS; ++i)
        thrd_join(threadId[i], NULL);
    
    return 0;
}


输出:

Perform one time.

注:使用Pelles C编译。


相关内容:
once_flag 包含供call_once函数使用标志的类型。
call_once 确保函数只被调用一次的函数。