]> git.ipfire.org Git - thirdparty/glibc.git/blame - nptl/pthread_rwlock_trywrlock.c
New pthread rwlock that is more scalable.
[thirdparty/glibc.git] / nptl / pthread_rwlock_trywrlock.c
CommitLineData
bfff8b1b 1/* Copyright (C) 2002-2017 Free Software Foundation, Inc.
76a50749
UD
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
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
59ba27a6
PE
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
76a50749
UD
18
19#include <errno.h>
20#include "pthreadP.h"
cc25c8b4 21#include <atomic.h>
76a50749 22
cc25c8b4 23/* See pthread_rwlock_common.c for an overview. */
76a50749 24int
c93c5dec 25__pthread_rwlock_trywrlock (pthread_rwlock_t *rwlock)
76a50749 26{
cc25c8b4
TR
27 /* When in a trywrlock, we can acquire the write lock if it is in states
28 #1 (idle and read phase) and #5 (idle and write phase), and also in #6
29 (readers waiting, write phase) if we prefer writers.
30 If we observe any other state, we are allowed to fail and do not need to
31 "synchronize memory" as specified by POSIX (hence relaxed MO is
32 sufficient for the first load and the CAS failure path).
33 We face a similar issue as in tryrdlock in that we need to both avoid
34 live-locks / starvation and must not fail spuriously (see there for
35 further comments) -- and thus must loop until we get a definitive
36 observation or state change. */
37 unsigned int r = atomic_load_relaxed (&rwlock->__data.__readers);
38 bool prefer_writer =
39 (rwlock->__data.__flags != PTHREAD_RWLOCK_PREFER_READER_NP);
40 while (((r & PTHREAD_RWLOCK_WRLOCKED) == 0)
41 && (((r >> PTHREAD_RWLOCK_READER_SHIFT) == 0)
42 || (prefer_writer && ((r & PTHREAD_RWLOCK_WRPHASE) != 0))))
76a50749 43 {
cc25c8b4
TR
44 /* Try to transition to states #7 or #8 (i.e., acquire the lock). */
45 if (atomic_compare_exchange_weak_acquire (
46 &rwlock->__data.__readers, &r,
47 r | PTHREAD_RWLOCK_WRPHASE | PTHREAD_RWLOCK_WRLOCKED))
48 {
49 atomic_store_relaxed (&rwlock->__data.__writers_futex, 1);
50 atomic_store_relaxed (&rwlock->__data.__wrphase_futex, 1);
51 atomic_store_relaxed (&rwlock->__data.__cur_writer,
52 THREAD_GETMEM (THREAD_SELF, tid));
53 return 0;
54 }
55 /* TODO Back-off. */
56 /* See above. */
76a50749 57 }
cc25c8b4 58 return EBUSY;
76a50749 59}
cc25c8b4 60
76a50749 61strong_alias (__pthread_rwlock_trywrlock, pthread_rwlock_trywrlock)