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.
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
<code>import threading as t</code>2. Thread usage
<code>tt = t.Thread(group=None, target=None, name=None, args=(), kwargs={}, daemon=None)</code>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:
<code>def xc():
for y in range(100):
print('运行中' + str(y))
tt = t.Thread(target=xc)
tt.start()
tt.join()</code>Multi‑thread example:
<code>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()</code>Thread Locks
To prevent race conditions, use Lock or RLock . A simple lock example:
<code># Acquire lock (blocking with optional timeout)
Lock.acquire(blocking=True, timeout=1)
# Release lock
Lock.release()</code>Example with a shared variable:
<code>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()</code>Deadlock example using two locks demonstrates the need for careful ordering.
Recursive lock ( RLock ) allows the same thread to acquire the lock multiple times:
<code>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()</code>Using with simplifies lock handling:
<code>with lock:
for i in range(10):
print(i)</code>Condition Variables
<code>Condition.acquire()
Condition.wait(timeout=None)
Condition.notify(num)
Condition.notify_all()</code>Example:
<code>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()</code>Semaphores
Bounded semaphore (limits releases to the initial value):
<code>b = t.BoundedSemaphore(value=1)
b.acquire()
b.release()</code>Unbounded semaphore has no upper limit:
<code>s = t.Semaphore()
s.acquire()
s.release()</code>Event
<code>event.set() # flag becomes True
event.clear() # flag becomes False
event.is_set() # check flag
event.wait(timeout=None)</code>Example demonstrating flag control:
<code>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)</code>Thread‑local storage
<code>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()</code>Timer
<code>def f():
print('start')
global t
tt = t.Timer(3, f)
tt.start()
f()</code>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.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.