Path: blob/main/cddl/contrib/opensolaris/tools/ctf/cvt/barrier.c
39586 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#ifdef illumos41#include <synch.h>42#endif43#include <stdio.h>4445#include "barrier.h"4647void48barrier_init(barrier_t *bar, int nthreads)49{50pthread_mutex_init(&bar->bar_lock, NULL);51#ifdef illumos52sema_init(&bar->bar_sem, 0, USYNC_THREAD, NULL);53#else54sem_init(&bar->bar_sem, 0, 0);55#endif5657bar->bar_numin = 0;58bar->bar_nthr = nthreads;59}6061int62barrier_wait(barrier_t *bar)63{64pthread_mutex_lock(&bar->bar_lock);6566if (++bar->bar_numin < bar->bar_nthr) {67pthread_mutex_unlock(&bar->bar_lock);68#ifdef illumos69sema_wait(&bar->bar_sem);70#else71sem_wait(&bar->bar_sem);72#endif7374return (0);7576} else {77int i;7879/* reset for next use */80bar->bar_numin = 0;81for (i = 1; i < bar->bar_nthr; i++)82#ifdef illumos83sema_post(&bar->bar_sem);84#else85sem_post(&bar->bar_sem);86#endif87pthread_mutex_unlock(&bar->bar_lock);8889return (1);90}91}929394