import threading def sing(): print('进入sing -----------------') for i in range(3): print('进入sing循环 -----------------') l1.acquire() print('sing上锁 -----------------') print('唱歌。。。') try: print('dance解锁 -----------------') l2.release() print('dance解锁成功 -----------------') except Exception: print('sing中dance解锁失败,重新开始循环----------------') pass def dance(): print('进入dance -----------------') for i in range(3): print('进入dance循环 -----------------') l2.acquire() print('dance上锁 -----------------') print('跳舞。。。') try: print('sing解锁 -----------------') l1.release() print('sing解锁成功 -----------------') except Exception: print('dance中sing解锁失败,重新开始循环----------------') pass if __name__ == '__main__': # sing() # dance() l1 = threading.Lock() print(l1) l2 = threading.Lock() print(l2) t1 = threading.Thread(target=sing) t2 = threading.Thread(target=dance) print('线程创建完毕--------') t1.start() print('线程1开始执行------') t2.start() print('线程2开始执行------') t1.join() print('线程1守护主线程-----') t2.join() print('线程2守护主线程-----')
这里我们暂且先不提全局解释器锁,从这个代码例子里我们可以看出,一个锁在上锁以后,如果在没有释放它的情况下再要对它上锁,他就会阻塞住,一直到它的锁被释放了以后才能够再次被上锁,这样就实现了两个线程的交替执行。