python如何使用多线程执行多个函数?

使用threading.Thread可创建线程并发执行函数,target指定目标函数,start()启动,join()等待完成;I/O密集型任务受益明显,CPU密集型受GIL限制;通过args或kwargs传参;多个线程可用列表统一管理启停;共享变量需用Lock保证线程安全,避免数据竞争。

Python 中可以用 threading.Thread 为每个函数创建一个线程,让它们并发执行。注意:由于全局解释器锁(GIL),多线程对 CPU 密集型任务提速有限,但对 I/O 密集型(如网络请求、文件读写)很有效。

基本用法:为每个函数启动一个线程

把目标函数传给 Threadtarget 参数,用 .start() 启动,用 .join() 等待完成:

import threading
import time

def func_a(): print("A 开始") time.sleep(2) print("A 结束")

def func_b(): print("B 开始") time.sleep(1) print("B 结束")

创建线程

t1 = threading.Thread(target=func_a) t2 = threading.Thread(target=func_b)

启动线程

t1.start() t2.start()

等待两个线程都结束

t1.join() t2.join()

print("全部完成")

传递参数给多线程函数

args(元组)或 kwargs(字典)传参:

def greet(name, times=1):
    for i in range(times):
        print(f"Hello, {name} ({i+1})")
        time.sleep(0.5)

t = threading.Thread(target=greet, args=("Alice",), kwargs={"times": 2}) t.start() t.join()

管理多个线程:用列表统一启停

适合同时运行 3 个以上函数,避免重复写 t1t2

  • 把所有 Thread 对象存进列表
  • 遍历调用 .start() 启动全部
  • 再遍历调用 .join() 等待全部结束
threads = []
for func in [func_a, func_b, greet]:
    if func == greet:
        t = threading.Thread(target=func, args=("Bob",))
    else:
        t = threading.Thread(target=func)
    threads.append(t)

for t in threads: t.start() for t in threads: t.join()

注意线程安全:共享变量要加锁

多个线程修改同一个变量(如计数器、列表)时,可能出错。用 threading.Lock 保护临界区:

counter = 0
lock = threading.Lock()

def increment(): global counter for _ in range(100000): with lock: # 自动 acquire/release counter += 1

t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment) t1.start(); t2.start() t1.join(); t2.join() print(counter) # 稳定输出 200000

基本上就这些。不复杂但容易忽略 join 和锁 —— 忘了 join 主线程会提前退出;忘了锁,数据就可能乱。