例子:
from threading import Thread,Lock
from time import sleep, ctime
global_num = []
def func1():
global global_num
for i in range(5):
sleep(1) #假设是最耗时的主过程
lock.acquire()#两个线程会最开始抢这个锁,拿到锁就会处于关锁,执行后面的程序,其他线程执行处于监听状态,等待这个线程开锁,再抢锁
global_num.append(1)
print('-----%s---func1----:global_num=%s--------
'%(ctime(),global_num))
lock.release()
def func2():
global global_num
for i in range(3):
sleep(1)
lock.acquire()
global_num.append(2)
print('-----%s---func2-----:global_num=%s========
'%(ctime(),global_num))
lock.release()
print('global_num=',global_num)
lock = Lock()
t1 = Thread(target=func1)
t1.start()
t2 = Thread(target=func2)
t2.start()
t1.join()
t2.join()
print('global_num=%s
'%global_num)