if io_bound:
if io_very_slow:
print("Use Asyncio")
else:
print("Use Threads")
else:
print("Multi Processing")
CPU bound ⇒ CPU密集 ⇒ CPU loading重 ⇒ 計算密集型
IO bound ⇒ IO密集 ⇒ IO loading重
終極目標
並行 vs 併發
進程 vs 線程
多進程 vs 多線程 when
死鎖
from threading import Thread,Lock
import time
mutexA=Lock()
mutexB=Lock()
class MyThread(Thread):
def run(self):
self.func1()
self.func2()
def func1(self):
mutexA.acquire()
print('\\033[41m%s 拿到A锁\\033[0m' %self.name)
mutexB.acquire()
print('\\033[42m%s 拿到B锁\\033[0m' %self.name)
mutexB.release()
mutexA.release()
def func2(self):
mutexB.acquire()
print('\\033[43m%s 拿到B锁\\033[0m' %self.name)
time.sleep(2)
mutexA.acquire()
print('\\033[44m%s 拿到A锁\\033[0m' %self.name)
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(5):
t=MyThread()
t.start()
#output
Thread-1 拿到A锁
Thread-1 拿到B锁
Thread-1 拿到B锁
Thread-2 拿到A锁
'''解析
首先, 5個thread開始跑
1. 假設thread3搶到了:首先執行thread3.func1獲得A鎖
這時候其他thread都在等待func1的A鎖所以卡住
2. thread3.fun1繼續獲得A鎖 => 釋放B鎖 => 釋放A鎖
這時候假設其他thread中thread1搶到了:執行thread1.func1搶到A鎖
thread2,4,5繼續等待func1的A鎖
3. thread3能夠繼續執行func2搶到B鎖 => sleep(2)
因為他在執行func2搶B鎖的時候,thread1正在執行func1搶A鎖,其他thread都還在等func1A
4. thread3睡完2秒 => 要搶func2中的A鎖
同時thread1要搶func1中的B鎖
這時thread3需要的A鎖在thread1手中無法被釋出(要等thread1獲得B鎖才能釋出)
thread1需要的B鎖在thread3中無法被釋出(要等thread3獲得A鎖才釋出)
5. 死鎖
'''