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