From 3083cf100ac78c5b2b2e5ebde5bdc2cac40cb706 Mon Sep 17 00:00:00 2001 From: Clark Gaebel Date: Wed, 2 Nov 2011 04:33:55 -0400 Subject: [PATCH 1/2] Cleaned up the critical section macros. --- src/util.h | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/util.h b/src/util.h index 178923727..4c966486f 100644 --- a/src/util.h +++ b/src/util.h @@ -243,19 +243,20 @@ public: pcs = &csIn; pcs->Enter(pszName, pszFile, nLine); } + + operator bool() const + { + return true; + } + ~CCriticalBlock() { pcs->Leave(); } }; -// WARNING: This will catch continue and break! -// break is caught with an assertion, but there's no way to detect continue. -// I'd rather be careful than suffer the other more error prone syntax. -// The compiler will optimise away all this loop junk. #define CRITICAL_BLOCK(cs) \ - for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \ - for (CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce; fcriticalblockonce=false) + if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__)) class CTryCriticalBlock { @@ -267,6 +268,12 @@ public: { pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL); } + + operator bool() const + { + return Entered(); + } + ~CTryCriticalBlock() { if (pcs) @@ -274,12 +281,11 @@ public: pcs->Leave(); } } - bool Entered() { return pcs != NULL; } + bool Entered() const { return pcs != NULL; } }; #define TRY_CRITICAL_BLOCK(cs) \ - for (bool fcriticalblockonce=true; fcriticalblockonce; assert(("break caught by TRY_CRITICAL_BLOCK!" && !fcriticalblockonce)), fcriticalblockonce=false) \ - for (CTryCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__); fcriticalblockonce && (fcriticalblockonce = criticalblock.Entered()); fcriticalblockonce=false) + if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__)) From f873b84d6e91407cb6c9ea292d16baed6ec07779 Mon Sep 17 00:00:00 2001 From: Clark Gaebel Date: Wed, 2 Nov 2011 18:10:41 -0400 Subject: [PATCH 2/2] Added simple critical section test cases. --- src/test/util_tests.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 8afc85c50..8c8b99e1b 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -8,6 +8,25 @@ using namespace std; BOOST_AUTO_TEST_SUITE(util_tests) +BOOST_AUTO_TEST_CASE(util_criticalsection) +{ + CCriticalSection cs; + + do { + CRITICAL_BLOCK(cs) + break; + + BOOST_ERROR("break was swallowed!"); + } while(0); + + do { + TRY_CRITICAL_BLOCK(cs) + break; + + BOOST_ERROR("break was swallowed!"); + } while(0); +} + BOOST_AUTO_TEST_CASE(util_MedianFilter) { CMedianFilter filter(5, 15);