C Resource Clean-Up in Multithreading Environment

To avoid duplicate object initialisation in #multithreading environment using threads#, C standard library threads.h provides the function call_once which has the following definition:

void call_once(once_flag flag, void (*func)(void) );

once_flag is a flag is used to notify the function call_once that the callback (defined as void (*func)(void) shown above) should only be called exactly once. As such, we can avoid multiple attempts to initialise the same object which in reality it just needs to be initialised one time.

For object destruction, it can be rather complicated if not using the function atexit provided by the standard library stdlib.h. The definition is shown as below:

int atexit(void (*func)(void));

Notes the similarity of the parameter (void (*func)(void)) to the function call_once. Pass any necessary callback that will be handling the resource clean-up for the thread.

#c #resource #multithreading