How to call a function once using call_once and threads in C

1 Answer

0 votes
#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()
 
*/

 



answered Dec 19, 2024 by avibootz
edited Dec 19, 2024 by avibootz

Related questions

1 answer 96 views
2 answers 243 views
1 answer 184 views
184 views asked May 18, 2018 by avibootz
1 answer 156 views
156 views asked Apr 5, 2024 by avibootz
1 answer 143 views
...