threads/one_time_init.cThis is threads/one_time_init.c, an example to accompany the book, The Linux Programming Interface. This file is not printed in the book; it is the solution to Exercise 31-1 (page 670). The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3. In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.
|
/* one_time_init.c The one_time_init() function implemented here performs the same task as the POSIX threads pthread_once() library function. */ #include <pthread.h> #include "tlpi_hdr.h" struct once_struct { /* Our equivalent of pthread_once_t */ pthread_mutex_t mtx; int called; }; #define ONCE_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 } struct once_struct once = ONCE_INITIALIZER;
static int one_time_init(struct once_struct *once_control, void (*init)(void)) { int s; s = pthread_mutex_lock(&(once_control->mtx)); if (s == -1) errExitEN(s, "pthread_mutex_lock"); if (!once_control->called) { (*init)(); once_control->called = 1; } s = pthread_mutex_unlock(&(once_control->mtx)); if (s == -1) errExitEN(s, "pthread_mutex_unlock"); return 0; }
/* Remaining code is for testing one_time_init() */ static void init_func() { /* We should see this message only once, no matter how many times one_time_init() is called */ printf("Called init_func()\n"); }
static void * threadFunc(void *arg) { /* The following allows us to verify that even if a single thread calls one_time_init() multiple times, init_func() is called only once */ one_time_init(&once, init_func); one_time_init(&once, init_func); return NULL; }
int main(int argc, char *argv[]) { pthread_t t1, t2; int s; /* Create two threads, both of which will call one_time_init() */ s = pthread_create(&t1, NULL, threadFunc, (void *) 1); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_create(&t2, NULL, threadFunc, (void *) 2); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_join(t1, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("First thread returned\n"); s = pthread_join(t2, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("Second thread returned\n"); exit(EXIT_SUCCESS); }
Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.