Created
August 31, 2011 17:54
-
-
Save saghul/1184190 to your computer and use it in GitHub Desktop.
Thread local and metaclass experiment
This file contains hidden or 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
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