Threading.Lock and its uses in Python

In Python you can spawn a new thread to perform a task, and then wait for that thread to finish with its task.

One of the reasons why programmers like to work with threads is that all of the threads share the same data. If you have a global variable “x”, and you start up a bunch of threads, all of those threads share the same value of “x”.  For example:

    import threading

    x = 12345
    y = 'hello'
    z = [10, 20, 30]

    class MyClass(threading.Thread):

    def run(self):
        tid = threading.get_ident()
        print("Thread {0} has x = {1}, y = {2}, z = {3}".format(tid, x,y,z))

    for i in range(5):
    t = MyClass()
    t.start()

In the above code, we create five instances of MyClass, each of which has a “run” method. We invoke that “run” method within a new thread with t.start(). Within each thread, we have access to all of our global data.

This might lead you to believe that you can modify data from within the threads. And that would be a very, very bad idea. This is because Python’s built-in data structures aren’t “thread safe.”  This means that certain operations require several low-level instructions, and that Python might start executing a different thread partway through those instructions. If A and B are both modifying the same data structure, then we’re in trouble.

Note: All text before this line is just a snippet of the article Threading.Lock and its uses in Python, published in the newsletter Better Developers. The author of the already mentioned article is Reuven M. Lerner. Subscribe today to Better Developers using this link.

Leave a Comment