Branch data Line data Source code
1 : : /*
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 : :
37 : : #if MICROPY_DEBUG_VERBOSE // print debugging info
38 : : #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 : : /****************************************************************/
46 : : // Lock object
47 : :
48 : : STATIC const mp_obj_type_t mp_type_thread_lock;
49 : :
50 : : typedef struct _mp_obj_thread_lock_t {
51 : : mp_obj_base_t base;
52 : : mp_thread_mutex_t mutex;
53 : : volatile bool locked;
54 : : } mp_obj_thread_lock_t;
55 : :
56 : 19 : STATIC mp_obj_thread_lock_t *mp_obj_new_thread_lock(void) {
57 : 19 : mp_obj_thread_lock_t *self = mp_obj_malloc(mp_obj_thread_lock_t, &mp_type_thread_lock);
58 : 19 : mp_thread_mutex_init(&self->mutex);
59 : 19 : self->locked = false;
60 : 19 : return self;
61 : : }
62 : :
63 : 4435 : STATIC mp_obj_t thread_lock_acquire(size_t n_args, const mp_obj_t *args) {
64 : 4435 : mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(args[0]);
65 : 4435 : bool wait = true;
66 [ + + ]: 4435 : if (n_args > 1) {
67 : 1 : wait = mp_obj_get_int(args[1]);
68 : : // TODO support timeout arg
69 : : }
70 : 4435 : MP_THREAD_GIL_EXIT();
71 : 4435 : int ret = mp_thread_mutex_lock(&self->mutex, wait);
72 : 4435 : MP_THREAD_GIL_ENTER();
73 [ + + ]: 4435 : if (ret == 0) {
74 : : return mp_const_false;
75 [ + - ]: 4434 : } else if (ret == 1) {
76 : 4434 : self->locked = true;
77 : 4434 : return mp_const_true;
78 : : } else {
79 : 0 : mp_raise_OSError(-ret);
80 : : }
81 : : }
82 : : STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread_lock_acquire);
83 : :
84 : 4433 : STATIC mp_obj_t thread_lock_release(mp_obj_t self_in) {
85 : 4433 : mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
86 [ + + ]: 4433 : if (!self->locked) {
87 : 1 : mp_raise_msg(&mp_type_RuntimeError, NULL);
88 : : }
89 : 4432 : self->locked = false;
90 : 4432 : MP_THREAD_GIL_EXIT();
91 : 4432 : mp_thread_mutex_unlock(&self->mutex);
92 : 4432 : MP_THREAD_GIL_ENTER();
93 : 4432 : return mp_const_none;
94 : : }
95 : : STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_release_obj, thread_lock_release);
96 : :
97 : 9 : STATIC mp_obj_t thread_lock_locked(mp_obj_t self_in) {
98 : 9 : mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
99 [ + + ]: 9 : return mp_obj_new_bool(self->locked);
100 : : }
101 : : STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_locked_obj, thread_lock_locked);
102 : :
103 : 4397 : STATIC mp_obj_t thread_lock___exit__(size_t n_args, const mp_obj_t *args) {
104 : 4397 : (void)n_args; // unused
105 : 4397 : return thread_lock_release(args[0]);
106 : : }
107 : : STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock___exit___obj, 4, 4, thread_lock___exit__);
108 : :
109 : : STATIC 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) },
113 : : { 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) },
115 : : };
116 : :
117 : : STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_table);
118 : :
119 : : STATIC MP_DEFINE_CONST_OBJ_TYPE(
120 : : mp_type_thread_lock,
121 : : MP_QSTR_lock,
122 : : MP_TYPE_FLAG_NONE,
123 : : locals_dict, &thread_lock_locals_dict
124 : : );
125 : :
126 : : /****************************************************************/
127 : : // _thread module
128 : :
129 : : STATIC size_t thread_stack_size = 0;
130 : :
131 : 2 : STATIC mp_obj_t mod_thread_get_ident(void) {
132 : 2 : return mp_obj_new_int_from_uint(mp_thread_get_id());
133 : : }
134 : : STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_get_ident_obj, mod_thread_get_ident);
135 : :
136 : 7 : STATIC mp_obj_t mod_thread_stack_size(size_t n_args, const mp_obj_t *args) {
137 : 7 : mp_obj_t ret = mp_obj_new_int_from_uint(thread_stack_size);
138 [ + + ]: 7 : if (n_args == 0) {
139 : 5 : thread_stack_size = 0;
140 : : } else {
141 : 2 : thread_stack_size = mp_obj_get_int(args[0]);
142 : : }
143 : 7 : return ret;
144 : : }
145 : : STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_stack_size_obj, 0, 1, mod_thread_stack_size);
146 : :
147 : : typedef struct _thread_entry_args_t {
148 : : mp_obj_dict_t *dict_locals;
149 : : mp_obj_dict_t *dict_globals;
150 : : size_t stack_size;
151 : : mp_obj_t fun;
152 : : size_t n_args;
153 : : size_t n_kw;
154 : : mp_obj_t args[];
155 : : } thread_entry_args_t;
156 : :
157 : 592 : STATIC void *thread_entry(void *args_in) {
158 : : // Execution begins here for a new thread. We do not have the GIL.
159 : :
160 : 592 : thread_entry_args_t *args = (thread_entry_args_t *)args_in;
161 : :
162 : 592 : mp_state_thread_t ts;
163 : 592 : mp_thread_set_state(&ts);
164 : :
165 : 592 : mp_stack_set_top(&ts + 1); // need to include ts in root-pointer scan
166 : 592 : mp_stack_set_limit(args->stack_size);
167 : :
168 : : #if MICROPY_ENABLE_PYSTACK
169 : : // TODO threading and pystack is not fully supported, for now just make a small stack
170 : : mp_obj_t mini_pystack[128];
171 : : mp_pystack_init(mini_pystack, &mini_pystack[128]);
172 : : #endif
173 : :
174 : : // The GC starts off unlocked on this thread.
175 : 592 : ts.gc_lock_depth = 0;
176 : :
177 : 592 : ts.mp_pending_exception = MP_OBJ_NULL;
178 : :
179 : : // set locals and globals from the calling context
180 : 592 : mp_locals_set(args->dict_locals);
181 : 592 : mp_globals_set(args->dict_globals);
182 : :
183 : 592 : MP_THREAD_GIL_ENTER();
184 : :
185 : : // signal that we are set up and running
186 : 592 : mp_thread_start();
187 : :
188 : : // TODO set more thread-specific state here:
189 : : // cur_exception (root pointer)
190 : :
191 : 591 : DEBUG_printf("[thread] start ts=%p args=%p stack=%p\n", &ts, &args, MP_STATE_THREAD(stack_top));
192 : :
193 : 591 : nlr_buf_t nlr;
194 [ + + ]: 591 : if (nlr_push(&nlr) == 0) {
195 : 590 : mp_call_function_n_kw(args->fun, args->n_args, args->n_kw, args->args);
196 : 579 : nlr_pop();
197 : : } else {
198 : : // uncaught exception
199 : : // check for SystemExit
200 : 5 : mp_obj_base_t *exc = (mp_obj_base_t *)nlr.ret_val;
201 [ + + ]: 5 : if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
202 : : // swallow exception silently
203 : : } else {
204 : : // print exception out
205 : 1 : mp_printf(MICROPY_ERROR_PRINTER, "Unhandled exception in thread started by ");
206 : 1 : mp_obj_print_helper(MICROPY_ERROR_PRINTER, args->fun, PRINT_REPR);
207 : 1 : mp_printf(MICROPY_ERROR_PRINTER, "\n");
208 : 1 : mp_obj_print_exception(MICROPY_ERROR_PRINTER, MP_OBJ_FROM_PTR(exc));
209 : : }
210 : : }
211 : :
212 : 584 : DEBUG_printf("[thread] finish ts=%p\n", &ts);
213 : :
214 : : // signal that we are finished
215 : 584 : mp_thread_finish();
216 : :
217 : 583 : MP_THREAD_GIL_EXIT();
218 : :
219 : 583 : return NULL;
220 : : }
221 : :
222 : 593 : STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) {
223 : : // This structure holds the Python function and arguments for thread entry.
224 : : // We copy all arguments into this structure to keep ownership of them.
225 : : // We must be very careful about root pointers because this pointer may
226 : : // disappear from our address space before the thread is created.
227 : 593 : thread_entry_args_t *th_args;
228 : :
229 : : // get positional arguments
230 : 593 : size_t pos_args_len;
231 : 593 : mp_obj_t *pos_args_items;
232 : 593 : mp_obj_get_array(args[1], &pos_args_len, &pos_args_items);
233 : :
234 : : // check for keyword arguments
235 [ + + ]: 593 : if (n_args == 2) {
236 : : // just position arguments
237 : 591 : th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len);
238 : 591 : th_args->n_kw = 0;
239 : : } else {
240 : : // positional and keyword arguments
241 [ + + ]: 2 : if (mp_obj_get_type(args[2]) != &mp_type_dict) {
242 : 1 : mp_raise_TypeError(MP_ERROR_TEXT("expecting a dict for keyword args"));
243 : : }
244 : 1 : mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map;
245 : 1 : th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used);
246 : 1 : th_args->n_kw = map->used;
247 : : // copy across the keyword arguments
248 [ + + ]: 3 : for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) {
249 [ + - ]: 2 : if (mp_map_slot_is_filled(map, i)) {
250 : 2 : th_args->args[n++] = map->table[i].key;
251 : 2 : th_args->args[n++] = map->table[i].value;
252 : : }
253 : : }
254 : : }
255 : :
256 : : // copy across the positional arguments
257 : 592 : th_args->n_args = pos_args_len;
258 : 592 : memcpy(th_args->args, pos_args_items, pos_args_len * sizeof(mp_obj_t));
259 : :
260 : : // pass our locals and globals into the new thread
261 : 592 : th_args->dict_locals = mp_locals_get();
262 : 592 : th_args->dict_globals = mp_globals_get();
263 : :
264 : : // set the stack size to use
265 : 592 : th_args->stack_size = thread_stack_size;
266 : :
267 : : // set the function for thread entry
268 : 592 : th_args->fun = args[0];
269 : :
270 : : // spawn the thread!
271 : 592 : return mp_obj_new_int_from_uint(mp_thread_create(thread_entry, th_args, &th_args->stack_size));
272 : : }
273 : : STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);
274 : :
275 : 2 : STATIC mp_obj_t mod_thread_exit(void) {
276 : 2 : mp_raise_type(&mp_type_SystemExit);
277 : : }
278 : : STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);
279 : :
280 : 19 : STATIC mp_obj_t mod_thread_allocate_lock(void) {
281 : 19 : return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
282 : : }
283 : : STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_allocate_lock_obj, mod_thread_allocate_lock);
284 : :
285 : : STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
286 : : { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__thread) },
287 : : { MP_ROM_QSTR(MP_QSTR_LockType), MP_ROM_PTR(&mp_type_thread_lock) },
288 : : { MP_ROM_QSTR(MP_QSTR_get_ident), MP_ROM_PTR(&mod_thread_get_ident_obj) },
289 : : { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
290 : : { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
291 : : { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
292 : : { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
293 : : };
294 : :
295 : : STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_table);
296 : :
297 : : const mp_obj_module_t mp_module_thread = {
298 : : .base = { &mp_type_module },
299 : : .globals = (mp_obj_dict_t *)&mp_module_thread_globals,
300 : : };
301 : :
302 : : MP_REGISTER_MODULE(MP_QSTR__thread, mp_module_thread);
303 : :
304 : : #endif // MICROPY_PY_THREAD
|