Welcome, guest | Sign In | My Account | Store | Cart

Python 2.4 introduces a new threading.local() type - a thread local storage. This is a simple demonstration of this.

Python, 20 lines
 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')

2 comments

Martin Miller 11 years, 3 months ago  # | flag

Here's a more self-contained example:

import threading

class ThreadLocalExample(threading.Thread):
    def __init__(self):
        super(ThreadLocalExample, self).__init__()
        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())

for i in range(4):
    t = ThreadLocalExample()
    t.start()
Martin Miller 11 years, 3 months ago  # | flag

Actually, this would be slightly more efficient:

import threading
threadinglocal = threading.local()

class ThreadLocalExample(threading.Thread):
    def __init__(self):
        super(ThreadLocalExample, self).__init__()

    def run(self):
        import random, time
        threadinglocal.foo = []
        for i in range(10):
            threadinglocal.foo.append(random.choice(range(10)))
            print threading.currentThread(), threadinglocal.foo
            # A small sleep to let the threads run in different orders
            time.sleep(random.random())

for i in range(4):
    t = ThreadLocalExample()
    t.start()