Python 3.x 中如何使用threading模块进行多线程管理
Python 3.x 中如何使用 threading 模块进行多线程管理
引言:在计算机领域,多线程是一种重要的编程模式,可以提高程序的并发性和执行效率。Python 语言提供了 threading 模块,方便开发者进行多线程的管理。本文将介绍如何使用 threading 模块进行多线程编程,并通过实例演示多线程的使用。
import threading count = 0 # 共享资源 lock = threading.Lock() # 互斥锁 def increase(): global count for _ in range(100000): lock.acquire() # 加锁 count += 1 lock.release() # 解锁 def decrease(): global count for _ in range(100000): lock.acquire() # 加锁 count -= 1 lock.release() # 解锁 if __name__ == '__main__': 1. 创建两个线程 t1 = threading.Thread(target=increase) t2 = threading.Thread(target=decrease) 1. 启动线程 t1.start() t2.start() 1. 等待线程结束 t1.join() t2.join() 1. 输出结果 print("count:", count)登录后复制
import threading count = 0 # 共享资源 lock = threading.Lock() # 互斥锁 condition = threading.Condition() # 条件变量 def produce(): global count while True: with condition: if count >= 10: condition.wait() # 释放锁并等待条件变量 count += 1 print("Produced 1 item") condition.notify() # 通知等待的线程 def consume(): global count while True: with condition: if count