Skip to content

Commit b4ba510

Browse files
pcercueiQuzarDC
authored andcommitted
mutex: Handle recursive/errcheck after trying to get lock
Speed up mutex locking for regular mutexes by handling recursive/errcheck mutexes after the atomic compare-and-swap. Signed-off-by: Paul Cercueil <paul@crapouillou.net>
1 parent 3ad0d86 commit b4ba510

1 file changed

Lines changed: 11 additions & 10 deletions

File tree

kernel/thread/mutex.c

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -144,17 +144,18 @@ int mutex_trylock(mutex_t *m) {
144144
}
145145

146146
static int mutex_trylock_thd(mutex_t *m, kthread_t *thd) {
147-
kthread_t *thd_none = NULL;
147+
kthread_t *previous_thd = NULL;
148148

149149
assert(m->type <= MUTEX_TYPE_RECURSIVE);
150150

151-
if(m->holder == thd) {
152-
if(m->type == MUTEX_TYPE_ERRORCHECK) {
153-
errno = EDEADLK;
154-
return -1;
155-
}
151+
if(atomic_compare_exchange_strong(&m->holder, &previous_thd, thd)) {
152+
m->count = 1;
153+
return 0;
154+
}
156155

156+
if(previous_thd == thd) {
157157
if(m->type == MUTEX_TYPE_RECURSIVE) {
158+
/* Recursive mutex, we can just increment normally. */
158159
if(m->count == INT_MAX) {
159160
errno = EAGAIN;
160161
return -1;
@@ -163,11 +164,11 @@ static int mutex_trylock_thd(mutex_t *m, kthread_t *thd) {
163164
++m->count;
164165
return 0;
165166
}
166-
}
167167

168-
if(atomic_compare_exchange_strong(&m->holder, &thd_none, thd)) {
169-
m->count = 1;
170-
return 0;
168+
if(m->type == MUTEX_TYPE_ERRORCHECK) {
169+
errno = EDEADLK;
170+
return -1;
171+
}
171172
}
172173

173174
/* We did not get the lock */

0 commit comments

Comments
 (0)