pthread_once.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Copyright (C) 2004-2013 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library. If not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include "pthreadP.h"
  15. #include <lowlevellock.h>
  16. unsigned long int __fork_generation attribute_hidden;
  17. static void
  18. clear_once_control (void *arg)
  19. {
  20. pthread_once_t *once_control = (pthread_once_t *) arg;
  21. *once_control = 0;
  22. lll_futex_wake (once_control, INT_MAX, LLL_PRIVATE);
  23. }
  24. int
  25. __pthread_once (pthread_once_t *once_control, void (*init_routine) (void))
  26. {
  27. for (;;)
  28. {
  29. int oldval;
  30. int newval;
  31. /* Pseudo code:
  32. newval = __fork_generation | 1;
  33. oldval = *once_control;
  34. if ((oldval & 2) == 0)
  35. *once_control = newval;
  36. Do this atomically.
  37. */
  38. do
  39. {
  40. newval = __fork_generation | 1;
  41. oldval = *once_control;
  42. if (oldval & 2)
  43. break;
  44. } while (atomic_compare_and_exchange_val_acq (once_control, newval, oldval) != oldval);
  45. /* Check if the initializer has already been done. */
  46. if ((oldval & 2) != 0)
  47. return 0;
  48. /* Check if another thread already runs the initializer. */
  49. if ((oldval & 1) == 0)
  50. break;
  51. /* Check whether the initializer execution was interrupted by a fork. */
  52. if (oldval != newval)
  53. break;
  54. /* Same generation, some other thread was faster. Wait. */
  55. lll_futex_wait (once_control, oldval, LLL_PRIVATE);
  56. }
  57. /* This thread is the first here. Do the initialization.
  58. Register a cleanup handler so that in case the thread gets
  59. interrupted the initialization can be restarted. */
  60. pthread_cleanup_push (clear_once_control, once_control);
  61. init_routine ();
  62. pthread_cleanup_pop (0);
  63. /* Say that the initialisation is done. */
  64. *once_control = __fork_generation | 2;
  65. /* Wake up all other threads. */
  66. lll_futex_wake (once_control, INT_MAX, LLL_PRIVATE);
  67. return 0;
  68. }
  69. weak_alias (__pthread_once, pthread_once)
  70. strong_alias (__pthread_once, __pthread_once_internal)