From e22bf659f3578837d9c33de9e69fddd09e800ddf Mon Sep 17 00:00:00 2001 From: EunBong Song Date: Thu, 13 Apr 2017 09:10:19 +0900 Subject: [PATCH] pthread: fix an error in destorynig a mutex This patch fixes error after a pthread has been canceled while holding the mutex. All credits should go to Gregory Nutt who wrote the original commit. Change-Id: Ifeb172d356ea7abce373d80057ee281d713df542 Signed-off-by: Gregory Nutt [Song: backported b0796446 from NuttX] Signed-off-by: EunBong Song --- os/kernel/pthread/pthread_mutexdestroy.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/os/kernel/pthread/pthread_mutexdestroy.c b/os/kernel/pthread/pthread_mutexdestroy.c index 002ba3f..d83b001 100644 --- a/os/kernel/pthread/pthread_mutexdestroy.c +++ b/os/kernel/pthread/pthread_mutexdestroy.c @@ -58,6 +58,7 @@ #include #include +#include #include #include #include @@ -123,13 +124,34 @@ int pthread_mutex_destroy(FAR pthread_mutex_t *mutex) /* Is the semaphore available? */ if (mutex->pid != -1) { - ret = EBUSY; +#ifndef CONFIG_DISABLE_SIGNALS + /* Verify that the PID still exists. We may be destroying the + * mutex after cancelling a pthread and the mutex may have been + * in a bad state owned by the dead pthread. + */ + + ret = kill(mutex->pid, 0); + if (ret < 0) { + /* That thread associated with the PID no longer exists */ + + mutex->pid = -1; + + /* Destroy the semaphore */ + + status = sem_destroy((FAR sem_t *)&mutex->sem); + ret = (status != OK) ? get_errno() : OK; + } else +#endif + { + ret = EBUSY; + } + } else { /* Destroy the semaphore */ status = sem_destroy((sem_t *)&mutex->sem); if (status != OK) { - ret = EINVAL; + ret = get_errno(); } } -- 2.7.4