threading
threading.Lock 同步原语 -- 锁
需要共享的数据操作时用
【1】.acquire() 获得
【2】.release() 释放
【3】支持上下文操作 with lock:
import threading
import time
import random
eggs = []
lock - threading.Lock()
def put_egg (n, lst):
lock.acqire()
for i in range (1,n+1)
time.sleep(random,randint(0,2))
lst.append(i)
lock.release()
//或:
def put_egg (n, lst):
with lock:
for i in range (1,n+1)
time.sleep(random,randint(0,2))
lst.append(i)
def main():
treads = []
for i in range (3):
t - threading.Thread (target = put_egg, args = (5, eggs))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print(eggs)