summaryrefslogtreecommitdiffstats
path: root/src/port/pthread_barrier_wait.c
blob: 9e59b3f636b2158f82ee9e09f577ef040d335525 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*-------------------------------------------------------------------------
 *
 * pthread_barrier_wait.c
 *    Implementation of pthread_barrier_t support for platforms lacking it.
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *    src/port/pthread_barrier_wait.c
 *
 *-------------------------------------------------------------------------
 */

#include "c.h"

#include "port/pg_pthread.h"

int
pthread_barrier_init(pthread_barrier_t *barrier, const void *attr, int count)
{
	int			error;

	barrier->sense = false;
	barrier->count = count;
	barrier->arrived = 0;
	if ((error = pthread_cond_init(&barrier->cond, NULL)) != 0)
		return error;
	if ((error = pthread_mutex_init(&barrier->mutex, NULL)) != 0)
	{
		pthread_cond_destroy(&barrier->cond);
		return error;
	}

	return 0;
}

int
pthread_barrier_wait(pthread_barrier_t *barrier)
{
	bool		initial_sense;

	pthread_mutex_lock(&barrier->mutex);

	/* We have arrived at the barrier. */
	barrier->arrived++;
	Assert(barrier->arrived <= barrier->count);

	/* If we were the last to arrive, release the others and return. */
	if (barrier->arrived == barrier->count)
	{
		barrier->arrived = 0;
		barrier->sense = !barrier->sense;
		pthread_mutex_unlock(&barrier->mutex);
		pthread_cond_broadcast(&barrier->cond);

		return PTHREAD_BARRIER_SERIAL_THREAD;
	}

	/* Wait for someone else to flip the sense. */
	initial_sense = barrier->sense;
	do
	{
		pthread_cond_wait(&barrier->cond, &barrier->mutex);
	} while (barrier->sense == initial_sense);

	pthread_mutex_unlock(&barrier->mutex);

	return 0;
}

int
pthread_barrier_destroy(pthread_barrier_t *barrier)
{
	pthread_cond_destroy(&barrier->cond);
	pthread_mutex_destroy(&barrier->mutex);
	return 0;
}