1/* Copyright (C) 2002-2017 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19#include <errno.h>
20#include "pthreadP.h"
21#include <atomic.h>
22#include <futex-internal.h>
23
24
25int
26pthread_barrier_destroy (pthread_barrier_t *barrier)
27{
28 struct pthread_barrier *bar = (struct pthread_barrier *) barrier;
29
30 /* Destroying a barrier is only allowed if no thread is blocked on it.
31 Thus, there is no unfinished round, and all modifications to IN will
32 have happened before us (either because the calling thread took part
33 in the most recent round and thus synchronized-with all other threads
34 entering, or the program ensured this through other synchronization).
35 We must wait until all threads that entered so far have confirmed that
36 they have exited as well. To get the notification, pretend that we have
37 reached the reset threshold. */
38 unsigned int count = bar->count;
39 unsigned int max_in_before_reset = BARRIER_IN_THRESHOLD
40 - BARRIER_IN_THRESHOLD % count;
41 /* Relaxed MO sufficient because the program must have ensured that all
42 modifications happen-before this load (see above). */
43 unsigned int in = atomic_load_relaxed (&bar->in);
44 /* Trigger reset. The required acquire MO is below. */
45 if (atomic_fetch_add_relaxed (&bar->out, max_in_before_reset - in) < in)
46 {
47 /* Not all threads confirmed yet that they have exited, so another
48 thread will perform a reset. Wait until that has happened. */
49 while (in != 0)
50 {
51 futex_wait_simple (&bar->in, in, bar->shared);
52 in = atomic_load_relaxed (&bar->in);
53 }
54 }
55 /* We must ensure that memory reuse happens after all prior use of the
56 barrier (specifically, synchronize-with the reset of the barrier or the
57 confirmation of threads leaving the barrier). */
58 atomic_thread_fence_acquire ();
59
60 return 0;
61}
62