blob: 975e7d1f6315c4a572f816668d3626b85444c24c [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
37#if 0 // 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/****************************************************************/
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) {
57 mp_obj_thread_lock_t *self = m_new_obj(mp_obj_thread_lock_t);
58 self->base.type = &mp_type_thread_lock;
59 mp_thread_mutex_init(&self->mutex);
60 self->locked = false;
61 return self;
62}
63
64STATIC mp_obj_t thread_lock_acquire(size_t n_args, const mp_obj_t *args) {
65 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(args[0]);
66 bool wait = true;
67 if (n_args > 1) {
68 wait = mp_obj_get_int(args[1]);
69 // TODO support timeout arg
70 }
Damien George234f07f2017-02-06 10:47:20 +110071 MP_THREAD_GIL_EXIT();
Damien George801d1b32016-04-25 11:21:48 +000072 int ret = mp_thread_mutex_lock(&self->mutex, wait);
Damien George234f07f2017-02-06 10:47:20 +110073 MP_THREAD_GIL_ENTER();
Damien George801d1b32016-04-25 11:21:48 +000074 if (ret == 0) {
75 return mp_const_false;
76 } else if (ret == 1) {
77 self->locked = true;
78 return mp_const_true;
79 } else {
Damien George3a0a7712016-10-07 13:31:59 +110080 mp_raise_OSError(-ret);
Damien George801d1b32016-04-25 11:21:48 +000081 }
82}
83STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread_lock_acquire);
84
85STATIC mp_obj_t thread_lock_release(mp_obj_t self_in) {
86 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
87 // TODO check if already unlocked
88 self->locked = false;
Damien George234f07f2017-02-06 10:47:20 +110089 MP_THREAD_GIL_EXIT();
Damien George801d1b32016-04-25 11:21:48 +000090 mp_thread_mutex_unlock(&self->mutex);
Damien George234f07f2017-02-06 10:47:20 +110091 MP_THREAD_GIL_ENTER();
Damien George801d1b32016-04-25 11:21:48 +000092 return mp_const_none;
93}
94STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_release_obj, thread_lock_release);
95
96STATIC mp_obj_t thread_lock_locked(mp_obj_t self_in) {
97 mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
98 return mp_obj_new_bool(self->locked);
99}
100STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_locked_obj, thread_lock_locked);
101
Damien George34fc0062016-04-25 11:33:53 +0000102STATIC mp_obj_t thread_lock___exit__(size_t n_args, const mp_obj_t *args) {
Damien George7f4658a2016-04-25 20:58:22 +0000103 (void)n_args; // unused
Damien George34fc0062016-04-25 11:33:53 +0000104 return thread_lock_release(args[0]);
105}
106STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock___exit___obj, 4, 4, thread_lock___exit__);
107
Damien George801d1b32016-04-25 11:21:48 +0000108STATIC const mp_rom_map_elem_t thread_lock_locals_dict_table[] = {
109 { MP_ROM_QSTR(MP_QSTR_acquire), MP_ROM_PTR(&thread_lock_acquire_obj) },
110 { MP_ROM_QSTR(MP_QSTR_release), MP_ROM_PTR(&thread_lock_release_obj) },
111 { MP_ROM_QSTR(MP_QSTR_locked), MP_ROM_PTR(&thread_lock_locked_obj) },
Damien George34fc0062016-04-25 11:33:53 +0000112 { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&thread_lock_acquire_obj) },
113 { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&thread_lock___exit___obj) },
Damien George801d1b32016-04-25 11:21:48 +0000114};
115
116STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_table);
117
118STATIC const mp_obj_type_t mp_type_thread_lock = {
119 { &mp_type_type },
120 .name = MP_QSTR_lock,
121 .locals_dict = (mp_obj_dict_t*)&thread_lock_locals_dict,
122};
123
124/****************************************************************/
Damien George27cc0772016-04-22 22:52:33 +0000125// _thread module
126
Damien George707f98f2016-04-25 09:02:47 +0000127STATIC size_t thread_stack_size = 0;
128
Damien George27cc0772016-04-22 22:52:33 +0000129STATIC mp_obj_t mod_thread_get_ident(void) {
130 return mp_obj_new_int_from_uint((uintptr_t)mp_thread_get_state());
131}
132STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_get_ident_obj, mod_thread_get_ident);
133
Damien George707f98f2016-04-25 09:02:47 +0000134STATIC mp_obj_t mod_thread_stack_size(size_t n_args, const mp_obj_t *args) {
135 mp_obj_t ret = mp_obj_new_int_from_uint(thread_stack_size);
136 if (n_args == 0) {
137 thread_stack_size = 0;
138 } else {
139 thread_stack_size = mp_obj_get_int(args[0]);
140 }
141 return ret;
142}
143STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_stack_size_obj, 0, 1, mod_thread_stack_size);
144
Damien George27cc0772016-04-22 22:52:33 +0000145typedef struct _thread_entry_args_t {
Damien Georgedf95f522016-05-30 16:56:51 +0100146 size_t stack_size;
Damien George27cc0772016-04-22 22:52:33 +0000147 mp_obj_t fun;
148 size_t n_args;
149 size_t n_kw;
Damien George722cff52016-05-04 09:51:01 +0000150 mp_obj_t args[];
Damien George27cc0772016-04-22 22:52:33 +0000151} thread_entry_args_t;
152
153STATIC void *thread_entry(void *args_in) {
Damien George4cec63a2016-05-26 10:42:53 +0000154 // Execution begins here for a new thread. We do not have the GIL.
155
Damien George27cc0772016-04-22 22:52:33 +0000156 thread_entry_args_t *args = (thread_entry_args_t*)args_in;
157
158 mp_state_thread_t ts;
159 mp_thread_set_state(&ts);
160
161 mp_stack_set_top(&ts + 1); // need to include ts in root-pointer scan
Damien Georgedf95f522016-05-30 16:56:51 +0100162 mp_stack_set_limit(args->stack_size);
Damien George27cc0772016-04-22 22:52:33 +0000163
Damien George4cec63a2016-05-26 10:42:53 +0000164 MP_THREAD_GIL_ENTER();
165
Damien George9172c0c2016-05-04 09:52:19 +0000166 // signal that we are set up and running
167 mp_thread_start();
168
Damien George27cc0772016-04-22 22:52:33 +0000169 // TODO set more thread-specific state here:
170 // mp_pending_exception? (root pointer)
171 // cur_exception (root pointer)
172 // dict_locals? (root pointer) uPy doesn't make a new locals dict for functions, just for classes, so it's different to CPy
173
174 DEBUG_printf("[thread] start ts=%p args=%p stack=%p\n", &ts, &args, MP_STATE_THREAD(stack_top));
175
176 nlr_buf_t nlr;
177 if (nlr_push(&nlr) == 0) {
178 mp_call_function_n_kw(args->fun, args->n_args, args->n_kw, args->args);
179 nlr_pop();
180 } else {
181 // uncaught exception
182 // check for SystemExit
Damien George3eb7a262016-04-23 12:24:44 +0000183 mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val;
184 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 +0000185 // swallow exception silently
186 } else {
187 // print exception out
188 mp_printf(&mp_plat_print, "Unhandled exception in thread started by ");
189 mp_obj_print_helper(&mp_plat_print, args->fun, PRINT_REPR);
190 mp_printf(&mp_plat_print, "\n");
Damien George3eb7a262016-04-23 12:24:44 +0000191 mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(exc));
Damien George27cc0772016-04-22 22:52:33 +0000192 }
193 }
194
195 DEBUG_printf("[thread] finish ts=%p\n", &ts);
196
Damien George9172c0c2016-05-04 09:52:19 +0000197 // signal that we are finished
198 mp_thread_finish();
199
Damien George4cec63a2016-05-26 10:42:53 +0000200 MP_THREAD_GIL_EXIT();
201
Damien George27cc0772016-04-22 22:52:33 +0000202 return NULL;
203}
204
205STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) {
Damien George722cff52016-05-04 09:51:01 +0000206 // This structure holds the Python function and arguments for thread entry.
207 // We copy all arguments into this structure to keep ownership of them.
208 // We must be very careful about root pointers because this pointer may
209 // disappear from our address space before the thread is created.
210 thread_entry_args_t *th_args;
211
212 // get positional arguments
Damien George27cc0772016-04-22 22:52:33 +0000213 mp_uint_t pos_args_len;
214 mp_obj_t *pos_args_items;
215 mp_obj_get_array(args[1], &pos_args_len, &pos_args_items);
Damien George722cff52016-05-04 09:51:01 +0000216
217 // check for keyword arguments
Damien George27cc0772016-04-22 22:52:33 +0000218 if (n_args == 2) {
219 // just position arguments
Damien George722cff52016-05-04 09:51:01 +0000220 th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len);
Damien George27cc0772016-04-22 22:52:33 +0000221 th_args->n_kw = 0;
Damien George27cc0772016-04-22 22:52:33 +0000222 } else {
223 // positional and keyword arguments
224 if (mp_obj_get_type(args[2]) != &mp_type_dict) {
Damien George7d0d7212016-10-17 12:17:37 +1100225 mp_raise_msg(&mp_type_TypeError, "expecting a dict for keyword args");
Damien George27cc0772016-04-22 22:52:33 +0000226 }
227 mp_map_t *map = &((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[2]))->map;
Damien George722cff52016-05-04 09:51:01 +0000228 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 +0000229 th_args->n_kw = map->used;
Damien George722cff52016-05-04 09:51:01 +0000230 // copy across the keyword arguments
Damien George27cc0772016-04-22 22:52:33 +0000231 for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) {
232 if (MP_MAP_SLOT_IS_FILLED(map, i)) {
Damien George722cff52016-05-04 09:51:01 +0000233 th_args->args[n++] = map->table[i].key;
234 th_args->args[n++] = map->table[i].value;
Damien George27cc0772016-04-22 22:52:33 +0000235 }
236 }
Damien George27cc0772016-04-22 22:52:33 +0000237 }
Damien George722cff52016-05-04 09:51:01 +0000238
239 // copy agross the positional arguments
240 th_args->n_args = pos_args_len;
241 memcpy(th_args->args, pos_args_items, pos_args_len * sizeof(mp_obj_t));
242
Damien Georgedf95f522016-05-30 16:56:51 +0100243 // set the stack size to use
244 th_args->stack_size = thread_stack_size;
245
Damien George722cff52016-05-04 09:51:01 +0000246 // set the function for thread entry
247 th_args->fun = args[0];
248
249 // spawn the thread!
Damien Georgedf95f522016-05-30 16:56:51 +0100250 mp_thread_create(thread_entry, th_args, &th_args->stack_size);
Damien George722cff52016-05-04 09:51:01 +0000251
Damien George27cc0772016-04-22 22:52:33 +0000252 return mp_const_none;
253}
254STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);
255
Damien George2dacd602016-04-25 09:15:21 +0000256STATIC mp_obj_t mod_thread_exit(void) {
257 nlr_raise(mp_obj_new_exception(&mp_type_SystemExit));
258}
259STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);
260
Damien George801d1b32016-04-25 11:21:48 +0000261STATIC mp_obj_t mod_thread_allocate_lock(void) {
262 return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
263}
264STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_allocate_lock_obj, mod_thread_allocate_lock);
265
Damien George27cc0772016-04-22 22:52:33 +0000266STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
267 { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__thread) },
Damien George801d1b32016-04-25 11:21:48 +0000268 { MP_ROM_QSTR(MP_QSTR_LockType), MP_ROM_PTR(&mp_type_thread_lock) },
Damien George27cc0772016-04-22 22:52:33 +0000269 { MP_ROM_QSTR(MP_QSTR_get_ident), MP_ROM_PTR(&mod_thread_get_ident_obj) },
Damien George707f98f2016-04-25 09:02:47 +0000270 { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
Damien George27cc0772016-04-22 22:52:33 +0000271 { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
Damien George2dacd602016-04-25 09:15:21 +0000272 { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
Damien George801d1b32016-04-25 11:21:48 +0000273 { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
Damien George27cc0772016-04-22 22:52:33 +0000274};
275
276STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_table);
277
278const mp_obj_module_t mp_module_thread = {
279 .base = { &mp_type_module },
Damien George27cc0772016-04-22 22:52:33 +0000280 .globals = (mp_obj_dict_t*)&mp_module_thread_globals,
281};
282
283#endif // MICROPY_PY_THREAD