@@ -120,22 +120,21 @@ void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
120120 * stack_size = 2048 ; // minimum stack size
121121 }
122122
123+ // allocate TCB, stack and linked-list node (must be outside thread_mutex lock)
124+ StaticTask_t * tcb = m_new (StaticTask_t , 1 );
125+ StackType_t * stack = m_new (StackType_t , * stack_size / sizeof (StackType_t ));
126+ thread_t * th = m_new_obj (thread_t );
127+
123128 mp_thread_mutex_lock (& thread_mutex , 1 );
124129
125130 // create thread
126- StackType_t * stack = m_new (StackType_t , * stack_size / sizeof (StackType_t ));
127- StaticTask_t * task_buf = m_new (StaticTask_t , 1 );
128- TaskHandle_t id = xTaskCreateStatic (freertos_entry , "Thread" , * stack_size / sizeof (void * ), arg , 2 , stack , task_buf );
131+ TaskHandle_t id = xTaskCreateStatic (freertos_entry , "Thread" , * stack_size / sizeof (void * ), arg , 2 , stack , tcb );
129132 if (id == NULL ) {
130133 mp_thread_mutex_unlock (& thread_mutex );
131134 nlr_raise (mp_obj_new_exception_msg (& mp_type_OSError , "can't create thread" ));
132135 }
133136
134- // adjust stack_size to provide room to recover from hitting the limit
135- * stack_size -= 512 ;
136-
137137 // add thread to linked list of all threads
138- thread_t * th = m_new_obj (thread_t );
139138 th -> id = id ;
140139 th -> ready = 0 ;
141140 th -> arg = arg ;
@@ -145,6 +144,9 @@ void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
145144 thread = th ;
146145
147146 mp_thread_mutex_unlock (& thread_mutex );
147+
148+ // adjust stack_size to provide room to recover from hitting the limit
149+ * stack_size -= 512 ;
148150}
149151
150152void mp_thread_finish (void ) {
0 commit comments