pthread_spin_lock.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /* A machine-specific version can define SPIN_LOCK_READS_BETWEEN_CMPXCHG
  18. to the number of plain reads that it's optimal to spin on between uses
  19. of atomic_compare_and_exchange_val_acq. If spinning forever is optimal
  20. then use -1. If no plain reads here would ever be optimal, use 0. */
  21. #define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
  22. int
  23. pthread_spin_lock (pthread_spinlock_t *lock)
  24. {
  25. /* atomic_exchange usually takes less instructions than
  26. atomic_compare_and_exchange. On the other hand,
  27. atomic_compare_and_exchange potentially generates less bus traffic
  28. when the lock is locked.
  29. We assume that the first try mostly will be successful, and we use
  30. atomic_exchange. For the subsequent tries we use
  31. atomic_compare_and_exchange. */
  32. if (atomic_exchange_acq (lock, 1) == 0)
  33. return 0;
  34. do
  35. {
  36. /* The lock is contended and we need to wait. Going straight back
  37. to cmpxchg is not a good idea on many targets as that will force
  38. expensive memory synchronizations among processors and penalize other
  39. running threads.
  40. On the other hand, we do want to update memory state on the local core
  41. once in a while to avoid spinning indefinitely until some event that
  42. will happen to update local memory as a side-effect. */
  43. if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
  44. {
  45. int wait = SPIN_LOCK_READS_BETWEEN_CMPXCHG;
  46. while (*lock != 0 && wait > 0)
  47. --wait;
  48. }
  49. else
  50. {
  51. while (*lock != 0)
  52. ;
  53. }
  54. }
  55. while (atomic_compare_and_exchange_val_acq (lock, 1, 0) != 0);
  56. return 0;
  57. }