Fundamentals 12 min read

Comprehensive Guide to Python Threading, Locks, Semaphores, Events and Timers

This article explains Python's threading module, demonstrating how to import it, create and manage single and multiple threads, use thread locks (Lock and RLock), condition variables, semaphores, events, thread‑local storage, and timers, providing complete code examples for each concept.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Comprehensive Guide to Python Threading, Locks, Semaphores, Events and Timers

The CPU's scheduling unit, or the thread, is the final executor of a program; in Python, threads are often considered limited due to the GIL, yet they remain useful for I/O‑bound tasks.

1. Import the threading module import threading as t 2. Thread usage

tt = t.Thread(group=None, target=None, name=None, args=(), kwargs={}, daemon=None)

Key methods include tt.start(), tt.getName(), tt.setName(), tt.is_alive(), tt.join(), and others. The module also provides t.active_count() and t.enumerate() for monitoring active threads.

3. Creating threads

Single‑thread example:

def xc():
    for y in range(100):
        print('运行中' + str(y))

tt = t.Thread(target=xc)
tt.start()
tt.join()

Multi‑thread example:

def xc(num):
    print('运行:' + str(num))

c = []
for y in range(100):
    tt = t.Thread(target=xc, args=(y,))
    tt.start()
    c.append(tt)
for x in c:
    x.join()

Thread Locks

To prevent race conditions, use Lock or RLock. A simple lock example:

# Acquire lock (blocking with optional timeout)
Lock.acquire(blocking=True, timeout=1)
# Release lock
Lock.release()

Example with a shared variable:

n = 10
lock = t.Lock()

def xc(num):
    lock.acquire()
    print('运行+:' + str(num + n))
    print('运行-:' + str(num - n))
    lock.release()

c = []
for y in range(10):
    tt = t.Thread(target=xc, args=(y,))
    tt.start()
    c.append(tt)
for x in c:
    x.join()

Deadlock example using two locks demonstrates the need for careful ordering.

Recursive lock ( RLock) allows the same thread to acquire the lock multiple times:

lock1 = t.RLock()
lock2 = t.RLock()

def xc(num):
    lock1.acquire()
    print('运行+:' + str(num + n))
    lock2.acquire()
    print('运行-:' + str(num - n))
    lock2.release()
    lock1.release()

Using with simplifies lock handling:

with lock:
    for i in range(10):
        print(i)

Condition Variables

Condition.acquire()
Condition.wait(timeout=None)
Condition.notify(num)
Condition.notify_all()

Example:

def ww(c):
    with c:
        print('init')
        c.wait(timeout=5)
        print('end')

def xx(c):
    with c:
        print('nono')
        c.notifyAll()
        print('start')
        c.notify(1)
        print('21')

c = t.Condition()
 t.Thread(target=ww, args=(c,)).start()
 t.Thread(target=xx, args=(c,)).start()

Semaphores

Bounded semaphore (limits releases to the initial value):

b = t.BoundedSemaphore(value=1)
b.acquire()
b.release()

Unbounded semaphore has no upper limit:

s = t.Semaphore()
s.acquire()
s.release()

Event

event.set()      # flag becomes True
event.clear()    # flag becomes False
event.is_set()   # check flag
event.wait(timeout=None)

Example demonstrating flag control:

import time
 e = t.Event()
 def ff(num):
     while True:
         if num < 5:
             e.clear()
             print('清空')
         if num >= 5:
             e.wait(timeout=1)
             e.set()
             print('启动')
             if e.isSet():
                 e.clear()
                 print('停止')
         if num == 10:
             e.wait(timeout=3)
             e.clear()
             print('退出')
             break
         num += 1
         time.sleep(2)
 ff(1)

Thread‑local storage

l = t.local()

def ff(num):
    l.x = 100
    for y in range(num):
        l.x += 3
    print(str(l.x))

for y in range(10):
    t.Thread(target=ff, args=(y,)).start()

Timer

def f():
    print('start')
    global t
    tt = t.Timer(3, f)
    tt.start()

f()

The article concludes that threading simplifies complex problems, especially for I/O‑bound tasks such as web crawling, and provides a thorough overview of all related concepts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonconcurrencyEventmultithreadingsemaphoreLockthreading
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.