lowlevellock.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Copyright (C) 2002 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, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #include <atomic.h>
  17. /* Implement generic mutex. Basic futex syscall support is required:
  18. lll_futex_wait(futex, value) - call sys_futex with FUTEX_WAIT
  19. and third parameter VALUE
  20. lll_futex_wake(futex, value) - call sys_futex with FUTEX_WAKE
  21. and third parameter VALUE
  22. */
  23. /* Mutex lock counter:
  24. bit 31 clear means unlocked;
  25. bit 31 set means locked.
  26. All code that looks at bit 31 first increases the 'number of
  27. interested threads' usage counter, which is in bits 0-30.
  28. All negative mutex values indicate that the mutex is still locked. */
  29. static inline void
  30. __generic_mutex_lock (int *mutex)
  31. {
  32. unsigned int v;
  33. /* Bit 31 was clear, we got the mutex. (this is the fastpath). */
  34. if (atomic_bit_test_set (mutex, 31) == 0)
  35. return;
  36. atomic_increment (mutex);
  37. while (1)
  38. {
  39. if (atomic_bit_test_set (mutex, 31) == 0)
  40. {
  41. atomic_decrement (mutex);
  42. return;
  43. }
  44. /* We have to wait now. First make sure the futex value we are
  45. monitoring is truly negative (i.e. locked). */
  46. v = *mutex;
  47. if (v >= 0)
  48. continue;
  49. lll_futex_wait (mutex, v);
  50. }
  51. }
  52. static inline void
  53. __generic_mutex_unlock (int *mutex)
  54. {
  55. /* Adding 0x80000000 to the counter results in 0 if and only if
  56. there are not other interested threads - we can return (this is
  57. the fastpath). */
  58. if (atomic_add_zero (mutex, 0x80000000))
  59. return;
  60. /* There are other threads waiting for this mutex, wake one of them
  61. up. */
  62. lll_futex_wake (mutex, 1);
  63. }
  64. #define lll_mutex_lock(futex) __generic_mutex_lock (&(futex))
  65. #define lll_mutex_unlock(futex) __generic_mutex_unlock (&(futex))