pthread_spin_lock.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* pthread_spin_lock -- lock a spin lock. Generic version.
  2. Copyright (C) 2012-2016 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 <atomic.h>
  16. #include "pthreadP.h"
  17. #define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
  18. int
  19. pthread_spin_lock (pthread_spinlock_t *lock)
  20. {
  21. /* atomic_exchange usually takes less instructions than
  22. atomic_compare_and_exchange. On the other hand,
  23. atomic_compare_and_exchange potentially generates less bus traffic
  24. when the lock is locked.
  25. We assume that the first try mostly will be successful, and we use
  26. atomic_exchange. For the subsequent tries we use
  27. atomic_compare_and_exchange. */
  28. if (atomic_exchange_acq (lock, 1) == 0)
  29. return 0;
  30. do
  31. {
  32. /* The lock is contended and we need to wait. Going straight back
  33. to cmpxchg is not a good idea on many targets as that will force
  34. expensive memory synchronizations among processors and penalize other
  35. running threads.
  36. On the other hand, we do want to update memory state on the local core
  37. once in a while to avoid spinning indefinitely until some event that
  38. will happen to update local memory as a side-effect. */
  39. if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
  40. {
  41. int wait = SPIN_LOCK_READS_BETWEEN_CMPXCHG;
  42. while (*lock != 0 && wait > 0)
  43. --wait;
  44. }
  45. else
  46. {
  47. while (*lock != 0)
  48. ;
  49. }
  50. }
  51. while (atomic_compare_and_exchange_val_acq (lock, 1, 0) != 0);
  52. return 0;
  53. }