from threading import Thread,Semaphoreimport timedef func(sem,a,b): sem.acquire() time.sleep(0.5) print(a+b) sem.release()sem = Semaphore(4)t_lst = []for i in range(10): t = Thread(target=func,args=(sem,i,i+5)) t.start() t_lst.append(t)for t in t_lst: t.join()print('主线程')
import time,randomfrom threading import Thread,Eventdef connect_db(e): count = 0 while count < 3: e.wait(0.5) if e.is_set() == True: print('连接至数据库') break else: count += 1 print('第%d次连接失败'%count) else: raise TimeoutError('连接超时')def check_web(e): time.sleep(random.randint(0,3)) e.set()e = Event()t1 = Thread(target=connect_db,args=(e,))t2 = Thread(target=check_web,args=(e,))t1.start()t2.start()