Skip to content

Commit b49d7e4

Browse files
committed
Properly handle a thread which terminates itself
In Thread::terminate() release the join semaphore before terminating the thread. This allows the join semaphore to be properly signaled in the case where a thread is terminating itself.
1 parent da3b07d commit b49d7e4

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

rtos/rtos/Thread.cpp

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,14 @@ osStatus Thread::terminate() {
101101
osStatus ret;
102102
_mutex.lock();
103103

104-
ret = osThreadTerminate(_tid);
104+
// Set the Thread's tid to NULL and
105+
// release the semaphore before terminating
106+
// since this thread could be terminating itself
107+
osThreadId local_id = _tid;
108+
_join_sem.release();
105109
_tid = (osThreadId)NULL;
106110

107-
// Wake threads joining the terminated thread
108-
_join_sem.release();
111+
ret = osThreadTerminate(local_id);
109112

110113
_mutex.unlock();
111114
return ret;
@@ -116,6 +119,14 @@ osStatus Thread::join() {
116119
if (ret < 0) {
117120
return osErrorOS;
118121
}
122+
123+
// The semaphore has been released so this thread is being
124+
// terminated or has been terminated. Once the mutex has
125+
// been locked it is ensured that the thread is deleted.
126+
_mutex.lock();
127+
MBED_ASSERT(NULL == _tid);
128+
_mutex.unlock();
129+
119130
// Release sem so any other threads joining this thread wake up
120131
_join_sem.release();
121132
return osOK;

0 commit comments

Comments
 (0)