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

source code of glibc/nptl/pthread_barrier_destroy.c