1 /* Unlock a rwlock. Generic version.
2 Copyright (C) 2000-2022 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 <https://www.gnu.org/licenses/>. */
18
19 #include <pthread.h>
20
21 #include <pt-internal.h>
22
23 /* Unlock *RWLOCK, rescheduling a waiting writer thread or, if there
24 are no threads waiting for a write lock, rescheduling the reader
25 threads. */
26 int
__pthread_rwlock_unlock(pthread_rwlock_t * rwlock)27 __pthread_rwlock_unlock (pthread_rwlock_t *rwlock)
28 {
29 struct __pthread *wakeup;
30
31 __pthread_spin_wait (&rwlock->__lock);
32
33 assert (__pthread_spin_trylock (&rwlock->__held) == EBUSY);
34
35 if (rwlock->__readers > 1)
36 /* There are other readers. */
37 {
38 rwlock->__readers--;
39 __pthread_spin_unlock (&rwlock->__lock);
40 return 0;
41 }
42
43 if (rwlock->__readers == 1)
44 /* Last reader. */
45 rwlock->__readers = 0;
46
47
48 /* Wake someone else up. Try the writer queue first, then the
49 reader queue if that is empty. */
50
51 if (rwlock->__writerqueue)
52 {
53 wakeup = rwlock->__writerqueue;
54 __pthread_dequeue (wakeup);
55
56 /* We do not unlock RWLOCK->held: we are transferring the ownership
57 to the thread that we are waking up. */
58
59 __pthread_spin_unlock (&rwlock->__lock);
60 __pthread_wakeup (wakeup);
61
62 return 0;
63 }
64
65 if (rwlock->__readerqueue)
66 {
67 unsigned n = 0;
68
69 __pthread_queue_iterate (rwlock->__readerqueue, wakeup)
70 n++;
71
72 {
73 struct __pthread *wakeups[n];
74 unsigned i = 0;
75
76 __pthread_dequeuing_iterate (rwlock->__readerqueue, wakeup)
77 wakeups[i++] = wakeup;
78
79 rwlock->__readers += n;
80 rwlock->__readerqueue = 0;
81
82 __pthread_spin_unlock (&rwlock->__lock);
83
84 for (i = 0; i < n; i++)
85 __pthread_wakeup (wakeups[i]);
86 }
87
88 return 0;
89 }
90
91
92 /* Noone is waiting. Just unlock it. */
93
94 __pthread_spin_unlock (&rwlock->__held);
95 __pthread_spin_unlock (&rwlock->__lock);
96 return 0;
97 }
98 weak_alias (__pthread_rwlock_unlock, pthread_rwlock_unlock);
99