Numworks Epsilon  1.4.1
Graphing Calculator Operating System
modthread.c
Go to the documentation of this file.
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 STATIC 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 
64 STATIC 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  }
72  int ret = mp_thread_mutex_lock(&self->mutex, wait);
74  if (ret == 0) {
75  return mp_const_false;
76  } else if (ret == 1) {
77  self->locked = true;
78  return mp_const_true;
79  } else {
80  mp_raise_OSError(-ret);
81  }
82 }
83 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread_lock_acquire);
84 
85 STATIC 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  if (!self->locked) {
89  }
90  self->locked = false;
92  mp_thread_mutex_unlock(&self->mutex);
94  return mp_const_none;
95 }
96 STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_release_obj, thread_lock_release);
97 
98 STATIC mp_obj_t thread_lock_locked(mp_obj_t self_in) {
99  mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in);
100  return mp_obj_new_bool(self->locked);
101 }
102 STATIC MP_DEFINE_CONST_FUN_OBJ_1(thread_lock_locked_obj, thread_lock_locked);
103 
104 STATIC mp_obj_t thread_lock___exit__(size_t n_args, const mp_obj_t *args) {
105  (void)n_args; // unused
106  return thread_lock_release(args[0]);
107 }
108 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock___exit___obj, 4, 4, thread_lock___exit__);
109 
110 STATIC const mp_rom_map_elem_t thread_lock_locals_dict_table[] = {
111  { MP_ROM_QSTR(MP_QSTR_acquire), MP_ROM_PTR(&thread_lock_acquire_obj) },
112  { MP_ROM_QSTR(MP_QSTR_release), MP_ROM_PTR(&thread_lock_release_obj) },
113  { MP_ROM_QSTR(MP_QSTR_locked), MP_ROM_PTR(&thread_lock_locked_obj) },
114  { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&thread_lock_acquire_obj) },
115  { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&thread_lock___exit___obj) },
116 };
117 
118 STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_table);
119 
120 STATIC const mp_obj_type_t mp_type_thread_lock = {
121  { &mp_type_type },
122  .name = MP_QSTR_lock,
123  .locals_dict = (mp_obj_dict_t*)&thread_lock_locals_dict,
124 };
125 
126 /****************************************************************/
127 // _thread module
128 
129 STATIC size_t thread_stack_size = 0;
130 
131 STATIC mp_obj_t mod_thread_get_ident(void) {
132  return mp_obj_new_int_from_uint((uintptr_t)mp_thread_get_state());
133 }
134 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_get_ident_obj, mod_thread_get_ident);
135 
136 STATIC mp_obj_t mod_thread_stack_size(size_t n_args, const mp_obj_t *args) {
137  mp_obj_t ret = mp_obj_new_int_from_uint(thread_stack_size);
138  if (n_args == 0) {
139  thread_stack_size = 0;
140  } else {
141  thread_stack_size = mp_obj_get_int(args[0]);
142  }
143  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 STATIC void *thread_entry(void *args_in) {
158  // Execution begins here for a new thread. We do not have the GIL.
159 
160  thread_entry_args_t *args = (thread_entry_args_t*)args_in;
161 
163  mp_thread_set_state(&ts);
164 
165  mp_stack_set_top(&ts + 1); // need to include ts in root-pointer scan
166  mp_stack_set_limit(args->stack_size);
167 
168  // set locals and globals from the calling context
169  mp_locals_set(args->dict_locals);
170  mp_globals_set(args->dict_globals);
171 
173 
174  // signal that we are set up and running
175  mp_thread_start();
176 
177  // TODO set more thread-specific state here:
178  // mp_pending_exception? (root pointer)
179  // cur_exception (root pointer)
180 
181  DEBUG_printf("[thread] start ts=%p args=%p stack=%p\n", &ts, &args, MP_STATE_THREAD(stack_top));
182 
183  nlr_buf_t nlr;
184  if (nlr_push(&nlr) == 0) {
185  mp_call_function_n_kw(args->fun, args->n_args, args->n_kw, args->args);
186  nlr_pop();
187  } else {
188  // uncaught exception
189  // check for SystemExit
190  mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val;
192  // swallow exception silently
193  } else {
194  // print exception out
195  mp_printf(MICROPY_ERROR_PRINTER, "Unhandled exception in thread started by ");
199  }
200  }
201 
202  DEBUG_printf("[thread] finish ts=%p\n", &ts);
203 
204  // signal that we are finished
205  mp_thread_finish();
206 
208 
209  return NULL;
210 }
211 
212 STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) {
213  // This structure holds the Python function and arguments for thread entry.
214  // We copy all arguments into this structure to keep ownership of them.
215  // We must be very careful about root pointers because this pointer may
216  // disappear from our address space before the thread is created.
217  thread_entry_args_t *th_args;
218 
219  // get positional arguments
220  size_t pos_args_len;
221  mp_obj_t *pos_args_items;
222  mp_obj_get_array(args[1], &pos_args_len, &pos_args_items);
223 
224  // check for keyword arguments
225  if (n_args == 2) {
226  // just position arguments
227  th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len);
228  th_args->n_kw = 0;
229  } else {
230  // positional and keyword arguments
231  if (mp_obj_get_type(args[2]) != &mp_type_dict) {
232  mp_raise_TypeError("expecting a dict for keyword args");
233  }
234  mp_map_t *map = &((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[2]))->map;
235  th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used);
236  th_args->n_kw = map->used;
237  // copy across the keyword arguments
238  for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) {
239  if (MP_MAP_SLOT_IS_FILLED(map, i)) {
240  th_args->args[n++] = map->table[i].key;
241  th_args->args[n++] = map->table[i].value;
242  }
243  }
244  }
245 
246  // copy agross the positional arguments
247  th_args->n_args = pos_args_len;
248  memcpy(th_args->args, pos_args_items, pos_args_len * sizeof(mp_obj_t));
249 
250  // pass our locals and globals into the new thread
251  th_args->dict_locals = mp_locals_get();
252  th_args->dict_globals = mp_globals_get();
253 
254  // set the stack size to use
255  th_args->stack_size = thread_stack_size;
256 
257  // set the function for thread entry
258  th_args->fun = args[0];
259 
260  // spawn the thread!
261  mp_thread_create(thread_entry, th_args, &th_args->stack_size);
262 
263  return mp_const_none;
264 }
265 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);
266 
267 STATIC mp_obj_t mod_thread_exit(void) {
269 }
270 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);
271 
272 STATIC mp_obj_t mod_thread_allocate_lock(void) {
273  return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
274 }
275 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_allocate_lock_obj, mod_thread_allocate_lock);
276 
277 STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
278  { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__thread) },
279  { MP_ROM_QSTR(MP_QSTR_LockType), MP_ROM_PTR(&mp_type_thread_lock) },
280  { MP_ROM_QSTR(MP_QSTR_get_ident), MP_ROM_PTR(&mod_thread_get_ident_obj) },
281  { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
282  { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
283  { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
284  { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
285 };
286 
287 STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_table);
288 
290  .base = { &mp_type_module },
291  .globals = (mp_obj_dict_t*)&mp_module_thread_globals,
292 };
293 
294 #endif // MICROPY_PY_THREAD
#define MICROPY_ERROR_PRINTER
Definition: mpconfig.h:538
NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg)
Definition: runtime.c:1448
const mp_obj_type_t mp_type_SystemExit
int DEBUG_printf(const char *fmt,...)
#define mp_const_none
Definition: obj.h:614
#define MP_DEFINE_CONST_DICT(dict_name, table_name)
Definition: obj.h:317
#define nlr_push(buf)
Definition: nlr.h:73
mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type)
Definition: objexcept.c:329
mp_obj_type_t * mp_obj_get_type(mp_const_obj_t o_in)
Definition: obj.c:40
#define MP_ROM_QSTR(q)
Definition: obj.h:241
unsigned int uintptr_t
Definition: stdint.h:14
#define MP_OBJ_FROM_PTR(p)
Definition: obj.h:233
#define MP_ROM_PTR(p)
Definition: obj.h:242
#define mp_const_true
Definition: obj.h:616
mp_obj_t key
Definition: obj.h:342
mp_obj_base_t base
Definition: obj.h:814
#define MP_STATE_THREAD(x)
Definition: mpstate.h:248
size_t alloc
Definition: obj.h:361
mp_int_t mp_obj_get_int(mp_const_obj_t arg)
Definition: obj.c:225
#define STATIC
Definition: mpconfig.h:1178
bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo)
Definition: objtype.c:1143
void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items)
Definition: obj.c:346
#define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name)
Definition: obj.h:285
#define m_new_obj_var(obj_type, var_type, var_num)
Definition: misc.h:62
#define mp_stack_set_limit(limit)
Definition: stackctrl.h:43
#define NULL
Definition: stddef.h:4
NORETURN void mp_raise_OSError(int errno_)
Definition: runtime.c:1464
void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind)
Definition: obj.c:59
mp_obj_t value
Definition: obj.h:343
mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value)
Definition: objint.c:343
args
Definition: i18n.py:175
#define nlr_pop()
Definition: nlr.h:74
#define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name)
Definition: obj.h:297
const mp_obj_module_t mp_module_thread
Definition: obj.h:356
void * ret_val
Definition: nlr.h:42
const mp_obj_type_t mp_type_type
Definition: objtype.c:969
#define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name)
Definition: obj.h:282
size_t used
Definition: obj.h:360
#define MP_OBJ_TO_PTR(o)
Definition: obj.h:228
Definition: nlr.h:39
const mp_obj_type_t mp_type_dict
Definition: objdict.c:552
#define MP_THREAD_GIL_EXIT()
Definition: mpthread.h:58
const mp_obj_type_t mp_type_module
Definition: objmodule.c:94
#define nlr_raise(val)
Definition: nlr.h:89
qstr name
Definition: obj.h:478
#define MP_THREAD_GIL_ENTER()
Definition: mpthread.h:57
uint64_t mp_obj_t
Definition: obj.h:39
mp_map_elem_t * table
Definition: obj.h:362
int mp_printf(const mp_print_t *print, const char *fmt,...)
Definition: mpprint.c:380
mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, size_t n_args, size_t n_kw, const mp_obj_t *args)
Definition: runtime.c:615
NORETURN void mp_raise_TypeError(const char *msg)
Definition: runtime.c:1460
#define m_new_obj(type)
Definition: misc.h:60
void mp_stack_set_top(void *top)
Definition: stackctrl.c:38
void * memcpy(void *dst, const void *src, size_t n)
Definition: memcpy.c:3
#define mp_const_false
Definition: obj.h:615
const mp_obj_type_t mp_type_RuntimeError
void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc)
Definition: obj.c:81