python學習筆記(62) Treading模塊
阿新 • • 發佈:2018-11-28
rlock bre 數據庫連接 else import 回收 map randint put
默認情況下主線程會等待子線程結束
t.deamon = Ture # 主線程結束,子線程隨之結束
守護進程隨著主進程代碼的執行結束而結束
守護線程會在主線程結束以後等待其他子線程的結束才結束
主進程在執行完自己的代碼以後(守護進程結束)不會立即結束,而是等待子進程結束以後,回收子進程資源
主線程必須在其他非守護線程運行完畢以後才能結束(守護進程此時結束),因為主線程的結束意味著進程的結束,進程整體的資源都將被回收
聯想join()
################################################
進程鎖並不常用,一般用線程鎖
科學家吃面問題(死鎖)
GIL鎖是加給線程,並不能完全保證數據安全(時間線輪轉)
Lock() # 互斥鎖
Rlock() # 遞歸鎖,拿幾個鑰匙加幾把鎖,在同一線程可以拿多次,為解決死鎖問題
fork_lock() = noodle_lock() = Rlock()
################################################
信號量Semaphore()
事件Event()
import time
import random
from threading import Thread,Event
def connect_db(e):
count = 0
while count < 3:
e.wait(1) # 等待1秒
if e.is_set():
print(‘連接數據庫中...‘)
break
else:
count += 1
print(‘第%s次失敗...‘%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()
###############################################
Condition # 條件,一種更復雜的鎖
c.acquire()
c.release()
c.wait()
c.notify(int) # 造一次性鑰匙
wait和notify必須都在ac和re之間
from threading import Thread,Condition
def func(con,i):
con.acquire()
con.wait()
print(‘在第%s個循環裏‘%i)
con.release()
con = Condition()
for i in range(10):
Thread(target=func,args=(con,i)).start()
while True:
num = int(input(‘>>>‘))
con.acquire()
con.notify(num)
con.release()
###############################################
定時器 Timer
Timer(2,func).start() #延時2秒開啟
python學習筆記(62) Treading模塊