1 /* pthread_spin_lock -- lock a spin lock. Generic version.
2 Copyright (C) 2012-2015 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
22 /* A machine-specific version can define SPIN_LOCK_READS_BETWEEN_CMPXCHG
23 to the number of plain reads that it's optimal to spin on between uses
24 of atomic_compare_and_exchange_val_acq. If spinning forever is optimal
25 then use -1. If no plain reads here would ever be optimal, use 0. */
26 #ifndef SPIN_LOCK_READS_BETWEEN_CMPXCHG
27 # warning machine-dependent file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG
28 # define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
32 pthread_spin_lock (pthread_spinlock_t
*lock
)
34 /* atomic_exchange usually takes less instructions than
35 atomic_compare_and_exchange. On the other hand,
36 atomic_compare_and_exchange potentially generates less bus traffic
37 when the lock is locked.
38 We assume that the first try mostly will be successful, and we use
39 atomic_exchange. For the subsequent tries we use
40 atomic_compare_and_exchange. */
41 if (atomic_exchange_acq (lock
, 1) == 0)
46 /* The lock is contended and we need to wait. Going straight back
47 to cmpxchg is not a good idea on many targets as that will force
48 expensive memory synchronizations among processors and penalize other
50 On the other hand, we do want to update memory state on the local core
51 once in a while to avoid spinning indefinitely until some event that
52 will happen to update local memory as a side-effect. */
53 if (SPIN_LOCK_READS_BETWEEN_CMPXCHG
>= 0)
55 int wait
= SPIN_LOCK_READS_BETWEEN_CMPXCHG
;
57 while (*lock
!= 0 && wait
> 0)
66 while (atomic_compare_and_exchange_val_acq (lock
, 1, 0) != 0);