xref: /illumos-gate/usr/src/test/libc-tests/tests/call_once.c (revision b36afad7ffe84071c2c6831936cc1c524bd1ca90)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2016 Joyent, Inc.
14  */
15 
16 /*
17  * Test call_once(3C)
18  */
19 
20 #include <threads.h>
21 #include <sys/debug.h>
22 
23 #define	CO_NTHREADS	32
24 
25 static int co_val = 41;
26 static mtx_t co_once_mtx;
27 static mtx_t co_mtx;
28 static boolean_t co_go = B_FALSE;
29 static once_flag co_once = ONCE_FLAG_INIT;
30 static cnd_t co_cnd;
31 
32 static void
co_once_func(void)33 co_once_func(void)
34 {
35 	VERIFY3S(mtx_lock(&co_once_mtx), ==, thrd_success);
36 	co_val++;
37 	VERIFY3S(mtx_unlock(&co_once_mtx), ==, thrd_success);
38 }
39 
40 /*ARGSUSED*/
41 static int
co_thr(void * arg)42 co_thr(void *arg)
43 {
44 	VERIFY3S(mtx_lock(&co_mtx), ==, thrd_success);
45 	while (co_go == B_FALSE) {
46 		(void) cnd_wait(&co_cnd, &co_mtx);
47 	}
48 	VERIFY3S(mtx_unlock(&co_mtx), ==, thrd_success);
49 	call_once(&co_once, co_once_func);
50 	return (0);
51 }
52 
53 int
main(void)54 main(void)
55 {
56 	int i;
57 	thrd_t threads[CO_NTHREADS];
58 
59 	VERIFY3S(mtx_init(&co_once_mtx, mtx_plain), ==, thrd_success);
60 	VERIFY3S(mtx_init(&co_mtx, mtx_plain), ==, thrd_success);
61 	VERIFY3S(cnd_init(&co_cnd), ==, thrd_success);
62 
63 	for (i = 0; i < CO_NTHREADS; i++) {
64 		VERIFY3S(thrd_create(&threads[i], co_thr, NULL), ==,
65 		    thrd_success);
66 	}
67 
68 	VERIFY3S(mtx_lock(&co_mtx), ==, thrd_success);
69 	co_go = B_TRUE;
70 	VERIFY3S(mtx_unlock(&co_mtx), ==, thrd_success);
71 	VERIFY3S(cnd_broadcast(&co_cnd), ==, thrd_success);
72 
73 	for (i = 0; i < CO_NTHREADS; i++) {
74 		VERIFY3S(thrd_join(threads[i], NULL), ==, thrd_success);
75 	}
76 	VERIFY3S(co_val, ==, 42);
77 
78 	return (0);
79 }
80