Thread Locks

Learn about thread locks in Python.

We'll cover the following...

In order to protect concurrent accesses to resources by multiple threads, Python provides threading.Lock.

For example, if we consider stdout as a resource where only one thread can have access at the same time, we need to use a threading.Lock object to synchronize the access to that resource. The example below illustrates how to use a lock to share access to stdout.

To run the application below, click Run and run the command python2 threading-lock.py.

If you want to update the source code in coding playgrounds, you need to click Run again after changing the code and repeat the instructions to run the application.

import threading

stdout_lock = threading.Lock()

def print_something(something):
    with stdout_lock:
        print(something)

t = threading.Thread(target=print_something, args=("hello",))
t.daemon = True
t.start()
print_something("thread started")
Threads using a lock

Now ...