xref: /netbsd-src/external/cddl/osnet/dist/tools/ctf/cvt/barrier.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 #ifdef HAVE_NBTOOL_CONFIG_H
24 #include "nbtool_config.h"
25 #endif
26 
27 /*
28  * Copyright 2002 Sun Microsystems, Inc.  All rights reserved.
29  * Use is subject to license terms.
30  */
31 
32 #pragma ident	"%Z%%M%	%I%	%E% SMI"
33 
34 /*
35  * This file implements a barrier, a synchronization primitive designed to allow
36  * threads to wait for each other at given points.  Barriers are initialized
37  * with a given number of threads, n, using barrier_init().  When a thread calls
38  * barrier_wait(), that thread blocks until n - 1 other threads reach the
39  * barrier_wait() call using the same barrier_t.  When n threads have reached
40  * the barrier, they are all awakened and sent on their way.  One of the threads
41  * returns from barrier_wait() with a return code of 1; the remaining threads
42  * get a return code of 0.
43  */
44 
45 #include <pthread.h>
46 #ifdef illumos
47 #include <synch.h>
48 #endif
49 #include <stdio.h>
50 
51 #include "barrier.h"
52 
53 void
54 barrier_init(barrier_t *bar, int nthreads)
55 {
56 	pthread_mutex_init(&bar->bar_lock, NULL);
57 #ifdef illumos
58 	sema_init(&bar->bar_sem, 0, USYNC_THREAD, NULL);
59 #else
60 	sem_init(&bar->bar_sem, 0, 0);
61 #endif
62 
63 	bar->bar_numin = 0;
64 	bar->bar_nthr = nthreads;
65 }
66 
67 int
68 barrier_wait(barrier_t *bar)
69 {
70 	pthread_mutex_lock(&bar->bar_lock);
71 
72 	if (++bar->bar_numin < bar->bar_nthr) {
73 		pthread_mutex_unlock(&bar->bar_lock);
74 #ifdef illumos
75 		sema_wait(&bar->bar_sem);
76 #else
77 		sem_wait(&bar->bar_sem);
78 #endif
79 
80 		return (0);
81 
82 	} else {
83 		int i;
84 
85 		/* reset for next use */
86 		bar->bar_numin = 0;
87 		for (i = 1; i < bar->bar_nthr; i++)
88 #ifdef illumos
89 			sema_post(&bar->bar_sem);
90 #else
91 			sem_post(&bar->bar_sem);
92 #endif
93 		pthread_mutex_unlock(&bar->bar_lock);
94 
95 		return (1);
96 	}
97 }
98