#include <stdio.h>
#include <threads.h>
// Calls a function exactly once,
// even if invoked from several threads.
void call_func_once(void) {
puts("called once");
}
static once_flag flag = ONCE_FLAG_INIT;
int func(void* data) {
puts("func()");
call_once(&flag, call_func_once);
}
int main(void)
{
thrd_t t1, t2, t3, t4;
// thrd_create = Creates a new thread executing the function func
// The function is invoked as func(arg).
thrd_create(&t1, func, NULL);
thrd_create(&t2, func, NULL);
thrd_create(&t3, func, NULL);
thrd_create(&t4, func, NULL);
// thrd_join() = join the thread t1-t4 by blocking
// until the other thread has terminated.
// Blocks the current thread until the thread
// t1-t4 finishes execution.
thrd_join(t1, NULL);
thrd_join(t2, NULL);
thrd_join(t3, NULL);
thrd_join(t4, NULL);
}
/*
run:
func()
called once
func()
func()
func()
*/