Python 2.4 introduces a new threading.local() type - a thread local storage. This is a simple demonstration of this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import threading
class ThreadLocalExample:
def __init__(self):
self.local = threading.local()
def run(self):
import random, time
self.local.foo = []
for i in range(10):
self.local.foo.append(random.choice(range(10)))
print threading.currentThread(), self.local.foo
# A small sleep to let the threads run in different orders
time.sleep(random.random())
example = ThreadLocalExample()
for i in range(4):
t = threading.Thread(target=example.run)
t.start()
|
Python 2.4 introduces a new thread-local storage object, accessed via threading.local. This code shows 4 threads, all accessing the same object (self.local) but seeing different results.
The local object is implemented in C for most thread implementations, and there is a fallback version in Python in Lib/_threading_local.py. The python version contains a very large and informative docstring, which you can read with 'import _threading_local ; help(_threading_local)' at an interactive prompt (or with 'pydoc _threading_local')
Here's a more self-contained example:
Actually, this would be slightly more efficient: