xref: /illumos-gate/usr/src/test/libc-tests/tests/call_once.c (revision 447b1e1fca22e4de5e04623965fbb1460857930c)
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
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
42 co_thr(void *arg)
43 {
44 	VERIFY3S(mtx_lock(&co_mtx), ==, thrd_success);
45 	while (co_go == B_FALSE)
46 		cnd_wait(&co_cnd, &co_mtx);
47 	VERIFY3S(mtx_unlock(&co_mtx), ==, thrd_success);
48 	call_once(&co_once, co_once_func);
49 	return (0);
50 }
51 
52 int
53 main(void)
54 {
55 	int i;
56 	thrd_t threads[CO_NTHREADS];
57 
58 	VERIFY3S(mtx_init(&co_once_mtx, mtx_plain), ==, thrd_success);
59 	VERIFY3S(mtx_init(&co_mtx, mtx_plain), ==, thrd_success);
60 	VERIFY3S(cnd_init(&co_cnd), ==, thrd_success);
61 
62 	for (i = 0; i < CO_NTHREADS; i++) {
63 		VERIFY3S(thrd_create(&threads[i], co_thr, NULL), ==,
64 		    thrd_success);
65 	}
66 
67 	VERIFY3S(mtx_lock(&co_mtx), ==, thrd_success);
68 	co_go = B_TRUE;
69 	VERIFY3S(mtx_unlock(&co_mtx), ==, thrd_success);
70 	VERIFY3S(cnd_broadcast(&co_cnd), ==, thrd_success);
71 
72 	for (i = 0; i < CO_NTHREADS; i++) {
73 		VERIFY3S(thrd_join(threads[i], NULL), ==, thrd_success);
74 	}
75 	VERIFY3S(co_val, ==, 42);
76 
77 	return (0);
78 }
79