allocate_once.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Concurrent allocation and initialization of a pointer.
  2. Copyright (C) 2018-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  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 <allocate_once.h>
  16. #include <stdlib.h>
  17. #include <stdbool.h>
  18. void *
  19. __libc_allocate_once_slow (void **place, void *(*allocate) (void *closure),
  20. void (*deallocate) (void *closure, void *ptr),
  21. void *closure)
  22. {
  23. void *result = allocate (closure);
  24. if (result == NULL)
  25. return NULL;
  26. /* This loop implements a strong CAS on *place, with acquire-release
  27. MO semantics, from a weak CAS with relaxed-release MO. */
  28. while (true)
  29. {
  30. /* Synchronizes with the acquire MO load in allocate_once. */
  31. void *expected = NULL;
  32. if (atomic_compare_exchange_weak_release (place, &expected, result))
  33. return result;
  34. /* The failed CAS has relaxed MO semantics, so perform another
  35. acquire MO load. */
  36. void *other_result = atomic_load_acquire (place);
  37. if (other_result == NULL)
  38. /* Spurious failure. Try again. */
  39. continue;
  40. /* We lost the race. Free what we allocated and return the
  41. other result. */
  42. if (deallocate == NULL)
  43. free (result);
  44. else
  45. deallocate (closure, result);
  46. return other_result;
  47. }
  48. return result;
  49. }
  50. libc_hidden_def (__libc_allocate_once_slow)