| 1 | #include <iostream>
|
|---|
| 2 | #include <boost/thread.hpp>
|
|---|
| 3 | #include <boost/thread/shared_mutex.hpp>
|
|---|
| 4 | #include <boost/thread/locks.hpp>
|
|---|
| 5 |
|
|---|
| 6 | using namespace std;
|
|---|
| 7 |
|
|---|
| 8 | class Test {
|
|---|
| 9 | public:
|
|---|
| 10 | static Test *Instance();
|
|---|
| 11 | virtual ~Test();
|
|---|
| 12 |
|
|---|
| 13 | private:
|
|---|
| 14 | Test();
|
|---|
| 15 | static Test *instance;
|
|---|
| 16 | static boost::shared_mutex instanceMutex;
|
|---|
| 17 | };
|
|---|
| 18 |
|
|---|
| 19 | Test *Test::instance = NULL;
|
|---|
| 20 | boost::shared_mutex Test::instanceMutex;
|
|---|
| 21 |
|
|---|
| 22 | Test::Test() { };
|
|---|
| 23 |
|
|---|
| 24 | Test *Test::Instance() {
|
|---|
| 25 | boost::upgrade_lock<boost::shared_mutex> lock(instanceMutex);
|
|---|
| 26 | if (!instance) {
|
|---|
| 27 | boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
|
|---|
| 28 | instance = new Test();
|
|---|
| 29 | }
|
|---|
| 30 | return instance;
|
|---|
| 31 | };
|
|---|
| 32 |
|
|---|
| 33 | Test::~Test() {
|
|---|
| 34 | boost::upgrade_lock<boost::shared_mutex> lock(instanceMutex);
|
|---|
| 35 | if (instance) {
|
|---|
| 36 | boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
|
|---|
| 37 | instance = NULL;
|
|---|
| 38 | }
|
|---|
| 39 | };
|
|---|
| 40 |
|
|---|
| 41 | int main() {
|
|---|
| 42 | Test *i = Test::Instance();
|
|---|
| 43 | delete i;
|
|---|
| 44 |
|
|---|
| 45 | return(0);
|
|---|
| 46 | }
|
|---|