一、利用多線程提高程序並發性
1、使用threading模塊創建線程
import threading
def func():
print("hello, world!")
thread = threading.Thread(target=func)
thread.start()
2、保證線程安全
對共享資源進行加鎖
import threading
class SharedCounter:
def __init__(self, val=0):
self.val = val
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.val += 1
def decrement(self):
with self.lock:
self.val -= 1
3、使用線程池提高效率
避免線程創建和銷毀的開銷
import concurrent.futures
def func(num):
return num * 2
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = [executor.submit(func, i) for i in range(10)]
for future in concurrent.futures.as_completed(results):
print(future.result())
二、利用協程提高程序並發性
1、使用asyncio模塊創建協程
import asyncio
async def func():
print("hello, world!")
asyncio.run(func())
2、使用asyncio中的Future對象
類似於線程中的future,用於異步調用函數
import asyncio
async def func():
return 1 + 2
coroutine = func()
loop = asyncio.get_event_loop()
result = loop.run_until_complete(coroutine)
print(result)
3、使用asyncio中的Event Loop
協程的調度中心,負責任務的調度和切換
import asyncio
async def func():
print("A")
await asyncio.sleep(1)
print("B")
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(func(), func(), func()))
三、比較多線程和協程
1、線程和協程的區別
線程是系統級別的,協程是程序級別的;線程切換需要系統介入,協程切換隻需要程序自己控制
2、適用場景的區別
IO密集型任務適合使用協程,CPU密集型任務適合使用多線程
3、優缺點的區別
多線程優點:多核CPU有優勢,缺點:線程切換需要系統介入,開銷大
協程優點:切換開銷小,缺點:單線程無法利用多核CPU
原創文章,作者:DQPK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/147229.html
微信掃一掃
支付寶掃一掃