From d700a0e8b13d534617dfe086f556d5b29c0c784d Mon Sep 17 00:00:00 2001 From: kevin Date: Mon, 12 Dec 2022 12:19:56 -0500 Subject: [PATCH] cwMutex.h/cpp : Added lock() with a timeout option. --- cwMutex.cpp | 28 ++++++++++++++++++++++++++++ cwMutex.h | 1 + 2 files changed, 29 insertions(+) diff --git a/cwMutex.cpp b/cwMutex.cpp index 6981df6..6486429 100644 --- a/cwMutex.cpp +++ b/cwMutex.cpp @@ -97,6 +97,34 @@ cw::rc_t cw::mutex::tryLock( handle_t h, bool& lockFlRef ) return rc; } +cw::rc_t cw::mutex::lock( handle_t h, unsigned timeout_milliseconds ) +{ + rc_t rc = kOkRC; + mutex_t* p = _handleToPtr(h); + int sysRc; + time::spec_t ts; + + time::get(ts); + time::advanceMs(ts,timeout_milliseconds); + + + switch(sysRc = pthread_mutex_timedlock(&p->mutex,&ts) ) + { + case 0: + rc = kOkRC; + break; + + case ETIMEDOUT: + rc = kTimeOutRC; + + default: + rc = cwLogSysError(kInvalidOpRC,sysRc,"Lock failed."); + } + + return rc; + +} + cw::rc_t cw::mutex::lock( handle_t h ) { rc_t rc = kOkRC; diff --git a/cwMutex.h b/cwMutex.h index 52a8053..15a4143 100644 --- a/cwMutex.h +++ b/cwMutex.h @@ -11,6 +11,7 @@ namespace cw rc_t destroy( handle_t& h ); rc_t tryLock( handle_t h, bool& lockFlRef ); + rc_t lock( handle_t h, unsigned timeout_milliseconds ); rc_t lock( handle_t h ); rc_t unlock( handle_t h );