Skip to content

Instantly share code, notes, and snippets.

@saghul
Created August 31, 2011 17:54
Show Gist options
  • Save saghul/1184190 to your computer and use it in GitHub Desktop.
Save saghul/1184190 to your computer and use it in GitHub Desktop.
Thread local and metaclass experiment
import threading
class ThreadLocalMeta(type):
"""Metaclass to keep a single class instance per thread"""
_local = threading.local()
def __call__(cls, *args, **kwargs):
try:
return getattr(ThreadLocalMeta._local, cls.__name__.lower())
except AttributeError:
instance = super(ThreadLocalMeta, cls).__call__()
setattr(ThreadLocalMeta._local, cls.__name__.lower(), instance)
return instance
class MyClass(object):
__metaclass__ = ThreadLocalMeta
def test():
print "I'm thread %s" % threading.current_thread()
obj1 = MyClass()
obj2 = MyClass()
assert(obj1 == obj2)
t1 = threading.Thread(target=test)
t2 = threading.Thread(target=test)
t1.start()
t2.start()
t1.join()
t2.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment