From 316dbb5eb8ee600f1941026ca2966b8902cdc443 Mon Sep 17 00:00:00 2001 From: Isaac Connor Date: Fri, 1 Jun 2018 11:27:35 -0400 Subject: [PATCH] Implement a RecursiveMutex class which is an explicit Recursive Mutex. Change the db mutex to a recursive Mutex --- src/zm_db.cpp | 6 +++--- src/zm_db.h | 2 +- src/zm_thread.cpp | 9 +++++++++ src/zm_thread.h | 41 ++++++++++++++++++++++++----------------- 4 files changed, 37 insertions(+), 21 deletions(-) diff --git a/src/zm_db.cpp b/src/zm_db.cpp index d4a927f3b..806ef8e5c 100644 --- a/src/zm_db.cpp +++ b/src/zm_db.cpp @@ -24,7 +24,7 @@ #include "zm_db.h" MYSQL dbconn; -Mutex db_mutex; +RecursiveMutex db_mutex; bool zmDbConnected = false; @@ -91,15 +91,15 @@ void zmDbClose() { } MYSQL_RES * zmDbFetch(const char * query) { - if ( ! zmDbConnected ) { + if ( !zmDbConnected ) { Error("Not connected."); return NULL; } db_mutex.lock(); if ( mysql_query(&dbconn, query) ) { - Error("Can't run query: %s", mysql_error(&dbconn)); db_mutex.unlock(); + Error("Can't run query: %s", mysql_error(&dbconn)); return NULL; } Debug(4, "Success running query: %s", query); diff --git a/src/zm_db.h b/src/zm_db.h index de47a6108..c707ad2b7 100644 --- a/src/zm_db.h +++ b/src/zm_db.h @@ -41,7 +41,7 @@ class zmDbRow { }; extern MYSQL dbconn; -extern Mutex db_mutex; +extern RecursiveMutex db_mutex; bool zmDbConnect(); void zmDbClose(); diff --git a/src/zm_thread.cpp b/src/zm_thread.cpp index 8bb854e26..03d048bea 100644 --- a/src/zm_thread.cpp +++ b/src/zm_thread.cpp @@ -95,6 +95,15 @@ bool Mutex::locked() { return( state == EBUSY ); } +RecursiveMutex::RecursiveMutex() { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + + if ( pthread_mutex_init(&mMutex, &attr) < 0 ) + Error("Unable to create pthread mutex: %s", strerror(errno)); +} + Condition::Condition( Mutex &mutex ) : mMutex( mutex ) { if ( pthread_cond_init( &mCondition, NULL ) < 0 ) throw ThreadException( stringtf( "Unable to create pthread condition: %s", strerror(errno) ) ); diff --git a/src/zm_thread.h b/src/zm_thread.h index e1facc6a5..0c41a93a5 100644 --- a/src/zm_thread.h +++ b/src/zm_thread.h @@ -59,27 +59,34 @@ public: }; class Mutex { -friend class Condition; + friend class Condition; -private: - pthread_mutex_t mMutex; + private: + pthread_mutex_t mMutex; -public: - Mutex(); - ~Mutex(); + public: + Mutex(); + ~Mutex(); -private: - pthread_mutex_t *getMutex() { - return( &mMutex ); - } + private: + pthread_mutex_t *getMutex() { + return &mMutex; + } -public: - int trylock(); - void lock(); - void lock( int secs ); - void lock( double secs ); - void unlock(); - bool locked(); + public: + int trylock(); + void lock(); + void lock( int secs ); + void lock( double secs ); + void unlock(); + bool locked(); +}; + +class RecursiveMutex : public Mutex { + private: + pthread_mutex_t mMutex; + public: + RecursiveMutex(); }; class ScopedMutex {