/*宏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;
}
|