如何在Python中创建并管理多线程?多线程相关问题案例
在Python中,由于全局解释器锁(GIL)的存在,多线程并不能真正实现并行计算。但是,你可以使用threading
模块创建和管理线程。
下面是一个简单的多线程案例:
import threading
# 定义一个要并发执行的函数
def concurrent_task(i):
print(f"Thread {i} is running the task..."))
# 这里可以执行任何耗时操作
time.sleep(2)
# 创建线程列表
threads = []
# 每个线程处理的任务数量
num_tasks = 5
# 遍历任务数,创建并启动线程
for i in range(num_tasks):
thread = threading.Thread(target=concurrent_task, args=(i+1),))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
在这个案例中,虽然每个任务都是并发执行的(由不同的线程处理),但由于GIL的存在,这些线程并没有真正实现并行计算。
还没有评论,来说两句吧...