发布于2026-07-21 阅读(0)
扫一扫,手机访问
在Ubuntu上做Python多线程开发,其实核心就一句话:用好标准库里的threading模块。下面这些技巧和代码示例,都是实际工程里反复验证过的,直接拿来用就行。

threading模块别想复杂了,第一步就是把模块请进来:
import threading
用threading.Thread类就能创建一个新线程。写个函数,把它塞进线程里跑,就这么简单。
def my_function():
print("Hello from a thread!")
# 创建一个线程
thread = threading.Thread(target=my_function)
# 启动线程
thread.start()
# 等待线程完成
thread.join()
很多时候函数需要参数,没问题,通过args传进去就行:
def my_function(arg1, arg2):
print(f"Arguments: {arg1}, {arg2}")
# 创建一个线程并传递参数
thread = threading.Thread(target=my_function, args=("Hello", "World"))
thread.start()
thread.join()
线程一多就容易分不清谁是谁,给每个线程起个名字,调试时一目了然。
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()
如果任务量比较大,一个个手动创建线程会非常低效。这时候线程池就派上用场了,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())
多个线程同时访问同一份数据,很容易出乱子。锁(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}")
条件变量适用于更复杂的场景:一个线程等待某个条件满足,另一个线程满足条件后通知它。典型的“生产者-消费者”模式就靠它。
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()
事件机制更轻量:一个线程可以设置事件,另一个线程等待事件发生。适合做简单的信号通知。
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多线程编程的常用场景。最后提醒一句:多线程编程最怕的就是竞态条件和数据不一致,共享资源一定要加锁,该同步的地方绝对不能偷懒。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8