在Ubuntu环境下进行Python多线程开发,核心要点就是善用标准库中的threading模块。以下技巧与代码示例均来自实际项目验证,可以直接应用于工程实践。

1. 导入threading模块
无需复杂操作,首先将模块引入即可:
import threading
2. 创建线程
使用threading.Thread类可以轻松创建新线程。编写一个函数,将其作为线程目标运行,步骤清晰明了。
def my_function():
print("Hello from a thread!")
# 创建一个线程
thread = threading.Thread(target=my_function)
# 启动线程
thread.start()
# 等待线程完成
thread.join()
3. 向线程函数传递参数
实际开发中函数往往需要参数,通过args参数传入即可:
def my_function(arg1, arg2):
print(f"Arguments: {arg1}, {arg2}")
# 创建一个线程并传递参数
thread = threading.Thread(target=my_function, args=("Hello", "World"))
thread.start()
thread.join()
4. 设置线程名称
当线程数量较多时,难以区分各自任务。为每个线程赋予名称,便于调试与追踪。
def my_function():
print(f"Hello from thread {threading.current_thread().name}")
thread = threading.Thread(target=my_function)
thread.name = "MyThread"
thread.start()
thread.join()
5. 使用线程池
面对大量任务,手动创建线程效率低下。此时线程池是更优选择,concurrent.futures模块提供了现成的实现方案:
import concurrent.futures
def my_function(arg):
return f"Processed {arg}"
# 创建一个线程池,最多同时运行3个工人
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
# 提交任务到线程池
futures = [executor.submit(my_function, i) for i in range(5)]
# 获取任务结果
for future in concurrent.futures.as_completed(futures):
print(future.result())
6. 线程同步
多个线程并发访问同一数据时容易引发数据混乱。锁(Lock)机制确保同一时刻只有一个线程修改共享资源,保证数据一致性。
import threading
lock = threading.Lock()
counter = 0
def increment_counter():
global counter
with lock:
counter += 1
threads = []
for _ in range(10):
thread = threading.Thread(target=increment_counter)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(f"Counter: {counter}")
7. 使用条件变量(Condition)
条件变量适用于更复杂的线程协作场景:一个线程等待特定条件满足,另一个线程满足条件后通知它。经典的“生产者-消费者”模式即依赖此机制。
import threading
condition = threading.Condition()
item = None
def producer():
global item
with condition:
item = "Produced Item"
condition.notify() # 通知等待的线程
def consumer():
global item
with condition:
condition.wait() # 等待通知
print(f"Consumed {item}")
producer_thread = threading.Thread(target=producer)
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start()
producer_thread.join()
consumer_thread.join()
8. 使用事件(Event)
事件机制更为轻量:一个线程可以设置事件,另一个线程等待事件触发。适合用于简单的信号通知场景。
import threading
import time
event = threading.Event()
def waiter():
print("Waiting for event...")
event.wait()
print("Event has happened!")
def trigger():
time.sleep(3)
print("Triggering event")
event.set()
waiter_thread = threading.Thread(target=waiter)
trigger_thread = threading.Thread(target=trigger)
waiter_thread.start()
trigger_thread.start()
waiter_thread.join()
trigger_thread.join()
以上技巧基本覆盖了Ubuntu系统下Python多线程编程的常见需求。最后提醒:多线程编程最怕竞态条件与数据不一致,共享资源务必加锁,该同步的地方绝不能省略。
