pthread_barrier_destroy.c 2.5 KB

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