Skip to content

Commit 8447843

Browse files
committed
Fix error handling when thread cannot be created
Update the Thread::start function to gracefully handle the failed creation of a thread when there are no TCBs left. This patch does the following: 1. Set memory handles to NULL after free to prevent double free 2. Post to the release semaphore so anything that tries to join this thread will join immediately 3. Remove dead return path since the new operator should never return NULL (it should trap instead)
1 parent 9e4a479 commit 8447843

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

rtos/rtos/Thread.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,7 @@ osStatus Thread::start(Callback<void()> task) {
8383
_thread_def.pthread = Thread::_thunk;
8484
if (_thread_def.stack_pointer == NULL) {
8585
_thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)];
86-
if (_thread_def.stack_pointer == NULL) {
87-
_mutex.unlock();
88-
return osErrorNoMemory;
89-
}
86+
MBED_ASSERT(_thread_def.stack_pointer != NULL);
9087
}
9188

9289
//Fill the stack with a magic word for maximum usage checking
@@ -97,8 +94,12 @@ osStatus Thread::start(Callback<void()> task) {
9794
_task = task;
9895
_tid = osThreadCreate(&_thread_def, this);
9996
if (_tid == NULL) {
100-
if (_dynamic_stack) delete[] (_thread_def.stack_pointer);
97+
if (_dynamic_stack) {
98+
delete[] (_thread_def.stack_pointer);
99+
_thread_def.stack_pointer = (uint32_t*)NULL;
100+
}
101101
_mutex.unlock();
102+
_join_sem.release();
102103
return osErrorResource;
103104
}
104105

@@ -355,6 +356,7 @@ Thread::~Thread() {
355356
#ifdef __MBED_CMSIS_RTOS_CM
356357
if (_dynamic_stack) {
357358
delete[] (_thread_def.stack_pointer);
359+
_thread_def.stack_pointer = (uint32_t*)NULL;
358360
}
359361
#endif
360362
}

0 commit comments

Comments
 (0)