From 38fb4cc3c48616f80816b65ca0e7fa4b5c7793d6 Mon Sep 17 00:00:00 2001 From: winlin Date: Fri, 12 Mar 2021 12:02:36 +0800 Subject: [PATCH] For #2188: Refine thread lock type to ERRORCHECK. 1. Set lock attribute type to PTHREAD_MUTEX_ERRORCHECK. 2. If dead lock, the pthread_mutex_lock return EDEADLK. 3. We assert fail if lock failed. --- trunk/src/app/srs_app_threads.cpp | 22 ++++++++++++++++++++-- trunk/src/app/srs_app_threads.hpp | 4 +++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/trunk/src/app/srs_app_threads.cpp b/trunk/src/app/srs_app_threads.cpp index 5ee814fd48b..7cdf0ea0976 100644 --- a/trunk/src/app/srs_app_threads.cpp +++ b/trunk/src/app/srs_app_threads.cpp @@ -34,8 +34,16 @@ using namespace std; SrsThreadMutex::SrsThreadMutex() { + // https://man7.org/linux/man-pages/man3/pthread_mutexattr_init.3.html + int r0 = pthread_mutexattr_init(&attr_); + srs_assert(!r0); + + // https://man7.org/linux/man-pages/man3/pthread_mutexattr_gettype.3p.html + r0 = pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_ERRORCHECK); + srs_assert(!r0); + // https://michaelkerrisk.com/linux/man-pages/man3/pthread_mutex_init.3p.html - int r0 = pthread_mutex_init(&lock_, NULL); + r0 = pthread_mutex_init(&lock_, &attr_); srs_assert(!r0); } @@ -43,11 +51,17 @@ SrsThreadMutex::~SrsThreadMutex() { int r0 = pthread_mutex_destroy(&lock_); srs_assert(!r0); + + r0 = pthread_mutexattr_destroy(&attr_); + srs_assert(!r0); } void SrsThreadMutex::lock() { // https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3p.html + // EDEADLK + // The mutex type is PTHREAD_MUTEX_ERRORCHECK and the current + // thread already owns the mutex. int r0 = pthread_mutex_lock(&lock_); srs_assert(!r0); } @@ -68,6 +82,10 @@ SrsThreadEntry::SrsThreadEntry() err = srs_success; } +SrsThreadEntry::~SrsThreadEntry() +{ +} + SrsThreadPool::SrsThreadPool() { entry_ = NULL; @@ -127,7 +145,7 @@ srs_error_t SrsThreadPool::execute(string label, srs_error_t (*start)(void* arg) pthread_t trd; int r0 = pthread_create(&trd, NULL, SrsThreadPool::start, entry); if (r0 != 0) { - entry->err = srs_error_new(ERROR_THREAD_CREATE, "create thread %s", label.c_str()); + entry->err = srs_error_new(ERROR_THREAD_CREATE, "create thread %s, r0=%d", label.c_str(), r0); return srs_error_copy(entry->err); } diff --git a/trunk/src/app/srs_app_threads.hpp b/trunk/src/app/srs_app_threads.hpp index ad86f58a706..6458e01f037 100644 --- a/trunk/src/app/srs_app_threads.hpp +++ b/trunk/src/app/srs_app_threads.hpp @@ -38,6 +38,7 @@ class SrsThreadMutex { private: pthread_mutex_t lock_; + pthread_mutexattr_t attr_; public: SrsThreadMutex(); virtual ~SrsThreadMutex(); @@ -78,8 +79,9 @@ class SrsThreadEntry pthread_t trd; // The exit error of thread. srs_error_t err; - +public: SrsThreadEntry(); + virtual ~SrsThreadEntry(); }; // Allocate a(or almost) fixed thread poll to execute tasks,