Skip to content

Commit 11ef1d1

Browse files
committed
rtos: Return an error when a Thread is re-used
Calling Thread::start multiple times leads to undefined behavior since the Thread class was not designed to handle being restarted. Return an error code if Thread::start is called a second time to prevent this behavior.
1 parent b0a1fd9 commit 11ef1d1

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

rtos/Thread.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ namespace rtos {
4444
void Thread::constructor(osPriority priority,
4545
uint32_t stack_size, unsigned char *stack_pointer) {
4646
_tid = 0;
47+
_finished = false;
4748
_dynamic_stack = (stack_pointer == NULL);
4849

4950
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
@@ -74,7 +75,7 @@ void Thread::constructor(Callback<void()> task,
7475
osStatus Thread::start(Callback<void()> task) {
7576
_mutex.lock();
7677

77-
if (_tid != 0) {
78+
if ((_tid != 0) || _finished) {
7879
_mutex.unlock();
7980
return osErrorParameter;
8081
}
@@ -117,6 +118,7 @@ osStatus Thread::terminate() {
117118
osThreadId local_id = _tid;
118119
_join_sem.release();
119120
_tid = (osThreadId)NULL;
121+
_finished = true;
120122

121123
ret = osThreadTerminate(local_id);
122124

@@ -367,6 +369,7 @@ void Thread::_thunk(const void * thread_ptr)
367369
t->_task();
368370
t->_mutex.lock();
369371
t->_tid = (osThreadId)NULL;
372+
t->_finished = true;
370373
t->_join_sem.release();
371374
// rtos will release the mutex automatically
372375
}

rtos/Thread.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ class Thread {
197197
/** Starts a thread executing the specified function.
198198
@param task function to be executed by this thread.
199199
@return status code that indicates the execution status of the function.
200+
@note a thread can only be started once
200201
*/
201202
osStatus start(mbed::Callback<void()> task);
202203

@@ -344,9 +345,10 @@ class Thread {
344345
mbed::Callback<void()> _task;
345346
osThreadId _tid;
346347
osThreadDef_t _thread_def;
347-
bool _dynamic_stack;
348348
Semaphore _join_sem;
349349
Mutex _mutex;
350+
bool _dynamic_stack;
351+
bool _finished;
350352
};
351353

352354
}

0 commit comments

Comments
 (0)