Skip to content

Instantly share code, notes, and snippets.

@dublindan
Created February 24, 2010 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dublindan/313570 to your computer and use it in GitHub Desktop.
Save dublindan/313570 to your computer and use it in GitHub Desktop.
#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