Skip to content

Commit 234f07f

Browse files
committed
py/modthread: Use system-provided mutexs for _thread locks.
It's more efficient using the system mutexs instead of synthetic ones with a busy-wait loop. The system can do proper scheduling and blocking of the threads waiting on the mutex.
1 parent 06a12ad commit 234f07f

1 file changed

Lines changed: 4 additions & 21 deletions

File tree

py/modthread.c

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,24 +44,19 @@
4444

4545
/****************************************************************/
4646
// Lock object
47-
// Note: with the GIL enabled we can easily synthesise a lock object
4847

4948
STATIC const mp_obj_type_t mp_type_thread_lock;
5049

5150
typedef struct _mp_obj_thread_lock_t {
5251
mp_obj_base_t base;
53-
#if !MICROPY_PY_THREAD_GIL
5452
mp_thread_mutex_t mutex;
55-
#endif
5653
volatile bool locked;
5754
} mp_obj_thread_lock_t;
5855

5956
STATIC mp_obj_thread_lock_t *mp_obj_new_thread_lock(void) {
6057
mp_obj_thread_lock_t *self = m_new_obj(mp_obj_thread_lock_t);
6158
self->base.type = &mp_type_thread_lock;
62-
#if !MICROPY_PY_THREAD_GIL
6359
mp_thread_mutex_init(&self->mutex);
64-
#endif
6560
self->locked = false;
6661
return self;
6762
}
@@ -73,20 +68,9 @@ STATIC mp_obj_t thread_lock_acquire(size_t n_args, const mp_obj_t *args) {
7368
wait = mp_obj_get_int(args[1]);
7469
// TODO support timeout arg
7570
}
76-
#if MICROPY_PY_THREAD_GIL
77-
if (self->locked) {
78-
if (!wait) {
79-
return mp_const_false;
80-
}
81-
do {
82-
MP_THREAD_GIL_EXIT();
83-
MP_THREAD_GIL_ENTER();
84-
} while (self->locked);
85-
}
86-
self->locked = true;
87-
return mp_const_true;
88-
#else
71+
MP_THREAD_GIL_EXIT();
8972
int ret = mp_thread_mutex_lock(&self->mutex, wait);
73+
MP_THREAD_GIL_ENTER();
9074
if (ret == 0) {
9175
return mp_const_false;
9276
} else if (ret == 1) {
@@ -95,17 +79,16 @@ STATIC mp_obj_t thread_lock_acquire(size_t n_args, const mp_obj_t *args) {
9579
} else {
9680
mp_raise_OSError(-ret);
9781
}
98-
#endif
9982
}
10083
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread_lock_acquire);
10184

10285
STATIC mp_obj_t thread_lock_release(mp_obj_t self_in) {
10386
mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
10487
// TODO check if already unlocked
10588
self->locked = false;
106-
#if !MICROPY_PY_THREAD_GIL
89+
MP_THREAD_GIL_EXIT();
10790
mp_thread_mutex_unlock(&self->mutex);
108-
#endif
91+
MP_THREAD_GIL_ENTER();
10992
return mp_const_none;
11093
}
11194
STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_release_obj, thread_lock_release);

0 commit comments

Comments
 (0)