Created
February 24, 2010 16:14
-
-
Save dublindan/313570 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <list> | |
#include <iostream> | |
// Replace with real mutex. | |
class Mutex | |
{ | |
public: | |
void lock () {} | |
void unlock () {} | |
}; | |
class Atomic | |
{ | |
private: | |
Mutex* mutex; | |
public: | |
Atomic (Mutex* m) : mutex(m) | |
{ | |
mutex->lock(); | |
} | |
~Atomic () | |
{ | |
mutex->unlock(); | |
} | |
}; | |
template <class T> | |
class ScopedGlobal | |
{ | |
private: | |
static std::list<T> global; | |
static Mutex mutex; | |
std::_List_iterator<T> iter; | |
public: | |
ScopedGlobal (T g) | |
{ | |
Atomic atom(&mutex); | |
iter = global.insert(global.end(), g); | |
} | |
~ScopedGlobal () | |
{ | |
Atomic atom(&mutex); | |
global.erase(iter); | |
} | |
static T& get () | |
{ | |
Atomic atom(&mutex); | |
return *iter; | |
} | |
}; | |
template <class T> | |
std::list<T> ScopedGlobal<T>::global; | |
template <class T> | |
Mutex ScopedGlobal<T>::mutex; | |
int main () | |
{ | |
ScopedGlobal<int> g(1); | |
std::cout << ScopedGlobal<int>::get() << "\n"; | |
{ | |
ScopedGlobal<int> g(2); | |
std::cout << ScopedGlobal<int>::get() << "\n"; | |
} | |
std::cout << ScopedGlobal<int>::get() << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment