Fundamentals 12 min read

Master Python Threading: From Basics to Advanced Techniques

This article provides a comprehensive guide to Python threading, covering core concepts such as thread creation, synchronization primitives like locks, RLocks, conditions, semaphores, events, local storage, and timers, complete with practical code examples and explanations of their usage and pitfalls.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Threading: From Basics to Advanced Techniques

Preface

Before diving into today's topics, let's briefly review threads, processes, and coroutines.

Thread

The CPU scheduler's execution unit, essentially the worker at the end of a program.

Python threads are often called "chicken ribs" because of the GIL; they are useful for I/O but limited for CPU‑bound tasks.

1. Import threading module

import threading as t

2. Using threads

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

Key methods:

tt.start() – activate the thread

tt.getName() / tt.setName() – get or set thread name

tt.is_alive() – check if running

tt.join() – wait for thread to finish

t.active_count() – number of running threads

t.enumerate() – list of running threads

t.current_thread().getName() – current thread name

3. Creating threads

Threads can be created with the Thread class or by subclassing and overriding run. Both single‑thread and multi‑thread examples are shown.

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))

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

for t in threads:
    t.join()

4. Thread locks

Locks prevent concurrent access to shared resources.

Lock

# Acquire lock (blocking, 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()

Deadlock example using two locks is also demonstrated.

RLock

Recursive lock allows the same thread to acquire the lock multiple times.

lock1 = t.RLock()
lock2 = t.RLock()
# usage similar to Lock but supports recursion

5. Condition variables

Used for signaling between threads.

cond = t.Condition()
cond.acquire()
cond.wait(timeout=None)
cond.notify()
cond.notify_all()
cond.release()

6. Semaphores

BoundedSemaphore enforces an upper limit; Semaphore does not.

# Bounded semaphore
b = t.BoundedSemaphore(value=1)
b.acquire()
b.release()

7. Event

Simple flag for thread communication.

event = t.Event()
event.set()      # flag True
event.clear()    # flag False
event.wait(timeout=None)

8. Thread‑local storage

Each thread can have its own independent variables.

l = t.local()
def worker(num):
    l.x = 100
    for _ in range(num):
        l.x += 3
    print(l.x)

9. Timer

Execute a function after a delay or repeatedly.

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

f()

Conclusion

By thoroughly exploring Python threading, we see how threads simplify complex problems and are especially useful for tasks like web crawling.

Thread illustration
Thread illustration
Lock illustration
Lock illustration
Bounded semaphore illustration
Bounded semaphore illustration
Event illustration
Event illustration
Thread-local illustration
Thread-local illustration
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.

PythonSynchronizationsemaphoreLockthreading
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.