From 1bdc4914f5d12d46891d09ba1c51c51fe24fe3a0 Mon Sep 17 00:00:00 2001 From: JoelKatz Date: Wed, 31 Oct 2012 15:48:17 -0700 Subject: [PATCH] Add InstanceCounter. --- newcoin.vcxproj | 1 + src/InstanceCounter.cpp | 15 ++++++++ src/InstanceCounter.h | 76 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 src/InstanceCounter.cpp create mode 100644 src/InstanceCounter.h diff --git a/newcoin.vcxproj b/newcoin.vcxproj index a2dd3bbb6..3109a074a 100644 --- a/newcoin.vcxproj +++ b/newcoin.vcxproj @@ -112,6 +112,7 @@ + diff --git a/src/InstanceCounter.cpp b/src/InstanceCounter.cpp new file mode 100644 index 000000000..564010282 --- /dev/null +++ b/src/InstanceCounter.cpp @@ -0,0 +1,15 @@ +#include "InstanceCounter.h" + +InstanceType* InstanceType::sHeadInstance = NULL; + +std::vector InstanceType::getInstanceCounts(int min) +{ + std::vector ret; + for (InstanceType* i = sHeadInstance; i != NULL; i = i->mNextInstance) + { + int c = i->getCount(); + if (c >= min) + ret.push_back(InstanceCount(i->getName(), c)); + } + return ret; +} diff --git a/src/InstanceCounter.h b/src/InstanceCounter.h new file mode 100644 index 000000000..62c8b91ba --- /dev/null +++ b/src/InstanceCounter.h @@ -0,0 +1,76 @@ +#ifndef INSTANCE_COUNTER__H +#define INSTANCE_COUNTER__H + +#include +#include + +#include + +#define DEFINE_INSTANCE(x) \ + extern InstanceType IT_##x; \ + class Instance_##x : private Instance \ + { \ + protected: \ + Instance_##x() : Instance(IT_##x) { ; } \ + } + +#define DECLARE_INSTANCE(x) \ + InstanceType IT_##x(#x); + +#define IS_INSTANCE(x) Instance_##x + +class InstanceType +{ +protected: + int mInstances; + std::string mName; + boost::mutex mLock; + + InstanceType* mNextInstance; + static InstanceType* sHeadInstance; + +public: + typedef std::pair InstanceCount; + + InstanceType(const char *n) : mInstances(0), mName(n) + { + mNextInstance = sHeadInstance; + sHeadInstance = this; + } + + void addInstance() + { + mLock.lock(); + ++mInstances; + mLock.unlock(); + } + void decInstance() + { + mLock.lock(); + --mInstances; + mLock.unlock(); + } + int getCount() + { + boost::mutex::scoped_lock(mLock); + return mInstances; + } + const std::string& getName() + { + return mName; + } + + static std::vector getInstanceCounts(int min = 1); +}; + +class Instance +{ +protected: + InstanceType& mType; + +public: + Instance(InstanceType& t) : mType(t) { mType.addInstance(); } + ~Instance() { mType.decInstance(); } +}; + +#endif