blob: 11d0405e710f082c65a6e7d401e3947bd9a82c30 [file] [log] [blame]
Damien George27cc0772016-04-22 22:52:33 +00001/*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27#include <stdio.h>
28#include <string.h>
29
30#include "py/runtime.h"
31#include "py/stackctrl.h"
32
33#if MICROPY_PY_THREAD
34
35#include "py/mpthread.h"
36
Stefan Naumannace9fb52017-07-24 18:55:14 +020037#if MICROPY_DEBUG_VERBOSE // print debugging info
Damien George27cc0772016-04-22 22:52:33 +000038#define DEBUG_PRINT (1)
39#define DEBUG_printf DEBUG_printf
40#else // don't print debugging info
41#define DEBUG_PRINT (0)
42#define DEBUG_printf(...) (void)0
43#endif
44
45/****************************************************************/
Damien George801d1b32016-04-25 11:21:48 +000046// Lock object
47
48STATIC const mp_obj_type_t mp_type_thread_lock;
49
50typedef struct _mp_obj_thread_lock_t {
51 mp_obj_base_t base;
52 mp_thread_mutex_t mutex;
Damien Georgec567afc2016-05-26 11:24:52 +000053 volatile bool locked;
Damien George801d1b32016-04-25 11:21:48 +000054} mp_obj_thread_lock_t;
55
56STATIC mp_obj_thread_lock_t *mp_obj_new_thread_lock(void) {
Jim Mussared0e7bfc82022-04-22 17:09:15 +100057 mp_obj_thread_lock_t *self = mp_obj_malloc(mp_obj_thread_lock_t, &mp_type_thread_lock);
Damien George801d1b32016-04-25 11:21:48 +000058 mp_thread_mutex_init(&self->mutex);
59 self->locked = false;
60 return self;
61}
62
63STATIC mp_obj_t thread_lock_acquire(size_t n_args, const mp_obj_t *args) {
64 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(args[0]);
65 bool wait = true;
66 if (n_args > 1) {
67 wait = mp_obj_get_int(args[1]);
68 // TODO support timeout arg
69 }
Damien George234f07f2017-02-06 10:47:20 +110070 MP_THREAD_GIL_EXIT();
Damien George801d1b32016-04-25 11:21:48 +000071 int ret = mp_thread_mutex_lock(&self->mutex, wait);
Damien George234f07f2017-02-06 10:47:20 +110072 MP_THREAD_GIL_ENTER();
Damien George801d1b32016-04-25 11:21:48 +000073 if (ret == 0) {
74 return mp_const_false;
75 } else if (ret == 1) {
76 self->locked = true;
77 return mp_const_true;
78 } else {
Damien George3a0a7712016-10-07 13:31:59 +110079 mp_raise_OSError(-ret);
Damien George801d1b32016-04-25 11:21:48 +000080 }
81}
82STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread_lock_acquire);
83
84STATIC mp_obj_t thread_lock_release(mp_obj_t self_in) {
85 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgee374cff2017-06-14 14:43:50 +100086 if (!self->locked) {
87 mp_raise_msg(&mp_type_RuntimeError, NULL);
88 }
Damien George801d1b32016-04-25 11:21:48 +000089 self->locked = false;
Damien George234f07f2017-02-06 10:47:20 +110090 MP_THREAD_GIL_EXIT();
Damien George801d1b32016-04-25 11:21:48 +000091 mp_thread_mutex_unlock(&self->mutex);
Damien George234f07f2017-02-06 10:47:20 +110092 MP_THREAD_GIL_ENTER();
Damien George801d1b32016-04-25 11:21:48 +000093 return mp_const_none;
94}
95STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_release_obj, thread_lock_release);
96
97STATIC mp_obj_t thread_lock_locked(mp_obj_t self_in) {
98 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
99 return mp_obj_new_bool(self->locked);
100}
101STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_locked_obj, thread_lock_locked);
102
Damien George34fc0062016-04-25 11:33:53 +0000103STATIC mp_obj_t thread_lock___exit__(size_t n_args, const mp_obj_t *args) {
Damien George7f4658a2016-04-25 20:58:22 +0000104 (void)n_args; // unused
Damien George34fc0062016-04-25 11:33:53 +0000105 return thread_lock_release(args[0]);
106}
107STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock___exit___obj, 4, 4, thread_lock___exit__);
108
Damien George801d1b32016-04-25 11:21:48 +0000109STATIC const mp_rom_map_elem_t thread_lock_locals_dict_table[] = {
110 { MP_ROM_QSTR(MP_QSTR_acquire), MP_ROM_PTR(&thread_lock_acquire_obj) },
111 { MP_ROM_QSTR(MP_QSTR_release), MP_ROM_PTR(&thread_lock_release_obj) },
112 { MP_ROM_QSTR(MP_QSTR_locked), MP_ROM_PTR(&thread_lock_locked_obj) },
Damien George34fc0062016-04-25 11:33:53 +0000113 { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&thread_lock_acquire_obj) },
114 { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&thread_lock___exit___obj) },
Damien George801d1b32016-04-25 11:21:48 +0000115};
116
117STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_table);
118
119STATIC const mp_obj_type_t mp_type_thread_lock = {
120 { &mp_type_type },
121 .name = MP_QSTR_lock,
Damien George69661f32020-02-27 15:36:53 +1100122 .locals_dict = (mp_obj_dict_t *)&thread_lock_locals_dict,
Damien George801d1b32016-04-25 11:21:48 +0000123};
124
125/****************************************************************/
Damien George27cc0772016-04-22 22:52:33 +0000126// _thread module
127
Damien George707f98f2016-04-25 09:02:47 +0000128STATIC size_t thread_stack_size = 0;
129
Damien George27cc0772016-04-22 22:52:33 +0000130STATIC mp_obj_t mod_thread_get_ident(void) {
131 return mp_obj_new_int_from_uint((uintptr_t)mp_thread_get_state());
132}
133STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_get_ident_obj, mod_thread_get_ident);
134
Damien George707f98f2016-04-25 09:02:47 +0000135STATIC mp_obj_t mod_thread_stack_size(size_t n_args, const mp_obj_t *args) {
136 mp_obj_t ret = mp_obj_new_int_from_uint(thread_stack_size);
137 if (n_args == 0) {
138 thread_stack_size = 0;
139 } else {
140 thread_stack_size = mp_obj_get_int(args[0]);
141 }
142 return ret;
143}
144STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_stack_size_obj, 0, 1, mod_thread_stack_size);
145
Damien George27cc0772016-04-22 22:52:33 +0000146typedef struct _thread_entry_args_t {
Damien George05fe66f2017-02-27 23:56:46 +1100147 mp_obj_dict_t *dict_locals;
148 mp_obj_dict_t *dict_globals;
Damien Georgedf95f522016-05-30 16:56:51 +0100149 size_t stack_size;
Damien George27cc0772016-04-22 22:52:33 +0000150 mp_obj_t fun;
151 size_t n_args;
152 size_t n_kw;
Damien George722cff52016-05-04 09:51:01 +0000153 mp_obj_t args[];
Damien George27cc0772016-04-22 22:52:33 +0000154} thread_entry_args_t;
155
156STATIC void *thread_entry(void *args_in) {
Damien George4cec63a2016-05-26 10:42:53 +0000157 // Execution begins here for a new thread. We do not have the GIL.
158
Damien George69661f32020-02-27 15:36:53 +1100159 thread_entry_args_t *args = (thread_entry_args_t *)args_in;
Damien George27cc0772016-04-22 22:52:33 +0000160
161 mp_state_thread_t ts;
162 mp_thread_set_state(&ts);
163
164 mp_stack_set_top(&ts + 1); // need to include ts in root-pointer scan
Damien Georgedf95f522016-05-30 16:56:51 +0100165 mp_stack_set_limit(args->stack_size);
Damien George27cc0772016-04-22 22:52:33 +0000166
Damien George02d830c2017-11-26 23:28:40 +1100167 #if MICROPY_ENABLE_PYSTACK
168 // TODO threading and pystack is not fully supported, for now just make a small stack
169 mp_obj_t mini_pystack[128];
170 mp_pystack_init(mini_pystack, &mini_pystack[128]);
171 #endif
172
Damien Georgeb6b39bf2021-05-04 23:56:43 +1000173 // The GC starts off unlocked on this thread.
174 ts.gc_lock_depth = 0;
175
David Lechnerca920f72021-05-10 21:53:22 -0500176 ts.mp_pending_exception = MP_OBJ_NULL;
177
Damien George05fe66f2017-02-27 23:56:46 +1100178 // set locals and globals from the calling context
179 mp_locals_set(args->dict_locals);
180 mp_globals_set(args->dict_globals);
181
Damien George4cec63a2016-05-26 10:42:53 +0000182 MP_THREAD_GIL_ENTER();
183
Damien George9172c0c2016-05-04 09:52:19 +0000184 // signal that we are set up and running
185 mp_thread_start();
186
Damien George27cc0772016-04-22 22:52:33 +0000187 // TODO set more thread-specific state here:
Damien George27cc0772016-04-22 22:52:33 +0000188 // cur_exception (root pointer)
Damien George27cc0772016-04-22 22:52:33 +0000189
190 DEBUG_printf("[thread] start ts=%p args=%p stack=%p\n", &ts, &args, MP_STATE_THREAD(stack_top));
191
192 nlr_buf_t nlr;
193 if (nlr_push(&nlr) == 0) {
194 mp_call_function_n_kw(args->fun, args->n_args, args->n_kw, args->args);
195 nlr_pop();
196 } else {
197 // uncaught exception
198 // check for SystemExit
Damien George69661f32020-02-27 15:36:53 +1100199 mp_obj_base_t *exc = (mp_obj_base_t *)nlr.ret_val;
Damien George3eb7a262016-04-23 12:24:44 +0000200 if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
Damien George27cc0772016-04-22 22:52:33 +0000201 // swallow exception silently
202 } else {
203 // print exception out
David Lechner62849b72017-09-24 20:15:48 -0500204 mp_printf(MICROPY_ERROR_PRINTER, "Unhandled exception in thread started by ");
205 mp_obj_print_helper(MICROPY_ERROR_PRINTER, args->fun, PRINT_REPR);
206 mp_printf(MICROPY_ERROR_PRINTER, "\n");
207 mp_obj_print_exception(MICROPY_ERROR_PRINTER, MP_OBJ_FROM_PTR(exc));
Damien George27cc0772016-04-22 22:52:33 +0000208 }
209 }
210
211 DEBUG_printf("[thread] finish ts=%p\n", &ts);
212
Damien George9172c0c2016-05-04 09:52:19 +0000213 // signal that we are finished
214 mp_thread_finish();
215
Damien George4cec63a2016-05-26 10:42:53 +0000216 MP_THREAD_GIL_EXIT();
217
Damien George27cc0772016-04-22 22:52:33 +0000218 return NULL;
219}
220
221STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) {
Damien George722cff52016-05-04 09:51:01 +0000222 // This structure holds the Python function and arguments for thread entry.
223 // We copy all arguments into this structure to keep ownership of them.
224 // We must be very careful about root pointers because this pointer may
225 // disappear from our address space before the thread is created.
226 thread_entry_args_t *th_args;
227
228 // get positional arguments
Damien George6213ad72017-03-25 19:35:08 +1100229 size_t pos_args_len;
Damien George27cc0772016-04-22 22:52:33 +0000230 mp_obj_t *pos_args_items;
231 mp_obj_get_array(args[1], &pos_args_len, &pos_args_items);
Damien George722cff52016-05-04 09:51:01 +0000232
233 // check for keyword arguments
Damien George27cc0772016-04-22 22:52:33 +0000234 if (n_args == 2) {
235 // just position arguments
Damien George722cff52016-05-04 09:51:01 +0000236 th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len);
Damien George27cc0772016-04-22 22:52:33 +0000237 th_args->n_kw = 0;
Damien George27cc0772016-04-22 22:52:33 +0000238 } else {
239 // positional and keyword arguments
240 if (mp_obj_get_type(args[2]) != &mp_type_dict) {
Jim Mussareddef76fe2020-03-02 22:35:22 +1100241 mp_raise_TypeError(MP_ERROR_TEXT("expecting a dict for keyword args"));
Damien George27cc0772016-04-22 22:52:33 +0000242 }
Damien George69661f32020-02-27 15:36:53 +1100243 mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map;
Damien George722cff52016-05-04 09:51:01 +0000244 th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used);
Damien George27cc0772016-04-22 22:52:33 +0000245 th_args->n_kw = map->used;
Damien George722cff52016-05-04 09:51:01 +0000246 // copy across the keyword arguments
Damien George27cc0772016-04-22 22:52:33 +0000247 for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) {
Damien George054dd332019-01-30 21:57:29 +1100248 if (mp_map_slot_is_filled(map, i)) {
Damien George722cff52016-05-04 09:51:01 +0000249 th_args->args[n++] = map->table[i].key;
250 th_args->args[n++] = map->table[i].value;
Damien George27cc0772016-04-22 22:52:33 +0000251 }
252 }
Damien George27cc0772016-04-22 22:52:33 +0000253 }
Damien George722cff52016-05-04 09:51:01 +0000254
David Lechner3e1bbea2020-01-24 15:23:44 -0600255 // copy across the positional arguments
Damien George722cff52016-05-04 09:51:01 +0000256 th_args->n_args = pos_args_len;
257 memcpy(th_args->args, pos_args_items, pos_args_len * sizeof(mp_obj_t));
258
Damien George05fe66f2017-02-27 23:56:46 +1100259 // pass our locals and globals into the new thread
260 th_args->dict_locals = mp_locals_get();
261 th_args->dict_globals = mp_globals_get();
262
Damien Georgedf95f522016-05-30 16:56:51 +0100263 // set the stack size to use
264 th_args->stack_size = thread_stack_size;
265
Damien George722cff52016-05-04 09:51:01 +0000266 // set the function for thread entry
267 th_args->fun = args[0];
268
269 // spawn the thread!
Damien Georgedf95f522016-05-30 16:56:51 +0100270 mp_thread_create(thread_entry, th_args, &th_args->stack_size);
Damien George722cff52016-05-04 09:51:01 +0000271
Damien George27cc0772016-04-22 22:52:33 +0000272 return mp_const_none;
273}
274STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);
275
Damien George2dacd602016-04-25 09:15:21 +0000276STATIC mp_obj_t mod_thread_exit(void) {
Damien George97eca382020-02-11 13:17:41 +1100277 mp_raise_type(&mp_type_SystemExit);
Damien George2dacd602016-04-25 09:15:21 +0000278}
279STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);
280
Damien George801d1b32016-04-25 11:21:48 +0000281STATIC mp_obj_t mod_thread_allocate_lock(void) {
282 return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
283}
284STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_allocate_lock_obj, mod_thread_allocate_lock);
285
Damien George27cc0772016-04-22 22:52:33 +0000286STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
287 { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__thread) },
Damien George801d1b32016-04-25 11:21:48 +0000288 { MP_ROM_QSTR(MP_QSTR_LockType), MP_ROM_PTR(&mp_type_thread_lock) },
Damien George27cc0772016-04-22 22:52:33 +0000289 { MP_ROM_QSTR(MP_QSTR_get_ident), MP_ROM_PTR(&mod_thread_get_ident_obj) },
Damien George707f98f2016-04-25 09:02:47 +0000290 { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
Damien George27cc0772016-04-22 22:52:33 +0000291 { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
Damien George2dacd602016-04-25 09:15:21 +0000292 { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
Damien George801d1b32016-04-25 11:21:48 +0000293 { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
Damien George27cc0772016-04-22 22:52:33 +0000294};
295
296STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_table);
297
298const mp_obj_module_t mp_module_thread = {
299 .base = { &mp_type_module },
Damien George69661f32020-02-27 15:36:53 +1100300 .globals = (mp_obj_dict_t *)&mp_module_thread_globals,
Damien George27cc0772016-04-22 22:52:33 +0000301};
302
Jim Mussaredd8d3e6a2022-04-20 16:14:22 +1000303MP_REGISTER_MODULE(MP_QSTR__thread, mp_module_thread, MICROPY_PY_THREAD);
304
Damien George27cc0772016-04-22 22:52:33 +0000305#endif // MICROPY_PY_THREAD