Saturday, March 23, 2013

Multi-threading in Python

What do you think you will get the from the above result?

import threading

class A(threading.local):
    def __init__(self, *args, **kwargs):
        self.val = 1

bla = A()


class Example(threading.Thread):

    def __init__(self, thread_id, value):
        self.thread_id = value
        self.value = value
        super(Example, self).__init__()

    def run(self):
        bla.val = self.value
        print "Thread: %s, id=%s" % (self.thread_id, bla.val)


example1 = Example(1, "A")
example2 = Example(2, "B")

example1.start()
example2.start()

example1.join()
example2.join()

print "Final value %s" % bla.val


The output is:

Thread: A, id=A
Thread: B, id=B
Final value 1

Thread-local storage (TLS) is actually implemented at the hardware level. This Stack Overflow article provides a link to how TLS is implemented on Linux.
http://people.redhat.com/drepper/tls.pdf

This link provides a good general explanation of the Python thread locals library.

No comments:

Post a Comment