Path: blob/main/cddl/contrib/opensolaris/tools/ctf/cvt/barrier.c
110319 views
/*1* CDDL HEADER START2*3* The contents of this file are subject to the terms of the4* Common Development and Distribution License, Version 1.0 only5* (the "License"). You may not use this file except in compliance6* with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or http://www.opensolaris.org/os/licensing.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/21/*22* Copyright 2002 Sun Microsystems, Inc. All rights reserved.23* Use is subject to license terms.24*/2526#pragma ident "%Z%%M% %I% %E% SMI"2728/*29* This file implements a barrier, a synchronization primitive designed to allow30* threads to wait for each other at given points. Barriers are initialized31* with a given number of threads, n, using barrier_init(). When a thread calls32* barrier_wait(), that thread blocks until n - 1 other threads reach the33* barrier_wait() call using the same barrier_t. When n threads have reached34* the barrier, they are all awakened and sent on their way. One of the threads35* returns from barrier_wait() with a return code of 1; the remaining threads36* get a return code of 0.37*/3839#include <pthread.h>40#include <stdio.h>4142#include "barrier.h"4344void45barrier_init(barrier_t *bar, int nthreads)46{47pthread_mutex_init(&bar->bar_lock, NULL);48pthread_cond_init(&bar->bar_cv, NULL);49bar->bar_numin = 0;50bar->bar_nthr = nthreads;51}5253int54barrier_wait(barrier_t *bar)55{56pthread_mutex_lock(&bar->bar_lock);5758if (++bar->bar_numin < bar->bar_nthr) {59pthread_cond_wait(&bar->bar_cv, &bar->bar_lock);60pthread_mutex_unlock(&bar->bar_lock);6162return (0);63} else {64/* reset for next use */65bar->bar_numin = 0;66pthread_cond_broadcast(&bar->bar_cv);67pthread_mutex_unlock(&bar->bar_lock);6869return (1);70}71}727374