python也提供了线程相关的并发原语,如锁threading.Lock,事件threading.Event,条件变量threading.Condition,信号量
threading.Semaphore.
其实这些Python对象本质上都是对pthread_mutex_t, pthread_condition_t的封装。
而多线程编程同步控制的本质和原理都是一样的。
因此虽然学习的是Python中如何进行多线程编程,其实本质上是语言无关的。
talk is cheap.
我们先通过2个具体的例子来分析和理解python中的多线程编程。
1.实现2个线程交替打印奇偶数
2.实现一个支持并发使用的环形队列
代码1:2个线程交替打印:
import threading
import time
c1 = threading.Condition() #用2个条件变量控制交替执行
c2 = threading.Condition()
def prt(i, wait, notify, name):
while True:
with wait:
wait.wait()
print(i, name)
i += 2
time.sleep(1)
with notify:
notify.notify_all()
t1 = threading.Thread(target=prt, args=(0, c1, c2,