跳到主要內容

Python 併發總結,多線程,多進程,異步IO

1 測量函數運行時間
import time 
def profile(func):
def wrapper(*args, **kwargs):
import time
start
= time.time()
func(
*args, **kwargs)
end
= time.time()
print 'COST: {}'.format(end - start)
return wrapper

@profile
def fib(n):
if n<= 2:
return 1
return fib(n-1) + fib(n-2)

fib(
35)

 

2 啟動多個線程,並等待完成   2.1 使用threading.enumerate()
import threading 
for i in range(2):
t
= threading.Thread(target=fib, args=(35,))
t.start()
main_thread
= threading.currentThread()

for t in threading.enumerate():
if t is main_thread:
continue
t.join()

 

2.2 先保存啟動的線程
threads = [] 
for i in range(5):
t
= Thread(target=foo, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
  3 使用信號量,限制同時能有幾個線程訪問臨界區
from threading import Semaphore 
import time

sema
= Semaphore(3)

def foo(tid):
with sema:
print('{} acquire sema'.format(tid))
wt
= random() * 2
time.sleep(wt)
print('{} release sema'.format(tid))

 

4 鎖,相當於信號量為1的情況
from threading import Thread Lock 
value
= 0
lock
= Lock()
def getlock():
global lock
with lock:
new
= value + 1
time.sleep(
0.001)
value
= new

 

  5 可重入鎖RLock     acquire() 可以不被阻塞的被同一個線程調用多次,release()需要和acquire()調用次數匹配才能釋放鎖 6 條件 Condition 一個線程發出信號,另一個線程等待信號 常用於生產者-消費者模型
import time 
import threading

def consumer(cond):
t
= threading.currentThread()
with cond:
cond.wait()
print("{}: Resource is available to sonsumer".format(t.name))

def producer(cond):
t
= threading.currentThread()
with cond:
print("{}: Making resource available".format(t.name))
cond.notifyAll()

condition
= threading.Condition()
c1
= threading.Thread(name='c1', target=consumer, args=(condition,))
c2
= threading.Thread(name='c2', target=consumer, args=(condition,))
p
= threading.Thread(name='p', target=producer, args=(condition,))

c1.start()
c2.start()
p.start()

 

  7 事件 Event 感覺和Condition 差不多
import time 
import threading
from random import randint

TIMEOUT
= 2

def consumer(event, l):
t
= threading.currentThread()
while 1:
event_is_set
= event.wait(TIMEOUT)
if event_is_set:
try:
integer
= l.pop()
print '{} popped from list by {}'.format(integer, t.name)
event.clear()
# 重置事件狀態
except IndexError: # 為了讓剛啟動時容錯
pass

def producer(event, l):
t
= threading.currentThread()
while 1:
integer
= randint(10, 100)
l.append(integer)
print '{} appended to list by {}'.format(integer, t.name)
event.set()
# 設置事件
time.sleep(1)

event
= threading.Event()
l
= []

threads
= []

for name in ('consumer1', 'consumer2'):
t
= threading.Thread(name=name, target=consumer, args=(event, l))
t.start()
threads.append(t)

p
= threading.Thread(name='producer1', target=producer, args=(event, l))
p.start()
threads.append(p)


for t in threads:
t.join()

 

  8 線程隊列  線程隊列有task_done() 和 join() 標準庫里的例子 往隊列內放結束標誌,注意do_work阻塞可能無法結束,需要用超時
import queue 
def worker():
while True:
item
= q.get()
if item is None:
break
do_work(item)
q.task_done()
q
= queue.Queue()
threads
= []
for i in range(num_worker_threads):
t
= threading.Thread(target=worker)
t.start()
threads.append(t)
for item in source():
q.put(item)
q.join()
for i in range(num_worker_threads):
q.put(None)
for t in threads:
t.join()

 

  9 優先級隊列 PriorityQueue
import threading 
from random import randint
from queue import PriorityQueue

q
= PriorityQueue()

def double(n):
return n * 2

def producer():
count
= 0
while 1:
if count > 5:
break
pri
= randint(0, 100)
print('put :{}'.format(pri))
q.put((pri, double, pri))
# (priority, func, args)
count += 1

def consumer():
while 1:
if q.empty():
break
pri, task, arg
= q.get()
print('[PRI:{}] {} * 2 = {}'.format(pri, arg, task(arg)))
q.task_done()
time.sleep(
0.1)

t
= threading.Thread(target=producer)
t.start()
time.sleep(
1)
t
= threading.Thread(target=consumer)
t.start()

 

  10 線程池 當線程執行相同的任務時用線程池 10.1 multiprocessing.pool 中的線程池
from multiprocessing.pool import ThreadPool 
pool
= ThreadPool(5)
pool.map(
lambda x: x**2, range(5))

 

10.2 multiprocessing.dummy
from multiprocessing.dummy import Pool

 

10.3 concurrent.futures.ThreadPoolExecutor
from concurrent.futures improt ThreadPoolExecutor 
from concurrent.futures import as_completed
import urllib.request

URLS
= ['http://www.baidu.com', 'http://www.hao123.com']

def load_url(url, timeout):
with urllib.request.urlopen(url, timeout
=timeout) as conn:
return conn.read()

with ThreadPoolExecutor(max_workers
=5) as executor:
future_to_url
= {executor.submit(load_url, url, 60): url for url in URLS}
for future in as_completed(future_to_url):
url
= future_to_url[future]
try:
data
= future.result()
execpt Exception as exc:
print("%r generated an exception: %s" % (url, exc))
else:
print("%r page is %d bytes" % (url, len(data)))

 

11 啟動多進程,等待多個進程結束
import multiprocessing 
jobs
= []
for i in range(2):
p
= multiprocessing.Process(target=fib, args=(12,))
p.start()
jobs.append(p)
for p in jobs:
p.join()

 

12 進程池 12.1 multiprocessing.Pool
from multiprocessing import Pool 
pool
= Pool(2)
pool.map(fib, [
36] * 2)

 

  12.2 concurrent.futures.ProcessPoolExecutor
from concurrent.futures import ProcessPoolExecutor 
import math

PRIMES
= [ 112272535095293, 112582705942171]

def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n
= int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True

if __name__ == "__main__":
with ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print("%d is prime: %s" % (number, prime))

 

  13 asyncio   13.1 最基本的示例,單個任務
import asyncio 

async
def hello():
print("Hello world!")
await asyncio.sleep(
1)
print("Hello again")

loop
= asyncio.get_event_loop()
loop.run_until_complete(hello())
loop.close()

 

13.2 最基本的示例,多個任務
import asyncio 

async
def hello():
print("Hello world!")
await asyncio.sleep(
1)
print("Hello again")

loop
= asyncio.get_event_loop()
tasks
= [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

 

  13.3 結合httpx 執行多個任務並接收返回結果 httpx 接口和 requests基本一致
import asyncio 
import httpx


async
def get_url():
r
= await httpx.get("http://www.baidu.com")
return r.status_code


loop
= asyncio.get_event_loop()
tasks
= [get_url() for i in range(10)]
results
= loop.run_until_complete(asyncio.gather(*tasks))
loop.close()


for num, result in zip(range(10), results):
print(num, result)

 

   本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【精選推薦文章】



如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!



想要讓你的商品在網路上成為最夯、最多人討論的話題?



網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線



不管是台北網頁設計公司台中網頁設計公司,全省皆有專員為您服務



想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師"嚨底家"!!



Orignal From: Python 併發總結,多線程,多進程,異步IO

留言

這個網誌中的熱門文章

強強聯手!攜手打造雲林縣Web3.0 領地方品牌進軍元宇宙

中華電信攜手國內最大Potato Media Web3.0社群共享平台,及品牌醫生果俐文創三方結合,透過經濟部「CBMP智慧雲遊跨域串連計畫」,協助品牌數位轉型,帶動品牌體驗情境、新商業模組升級與行動支付應用,第一站選在雲林縣當地原生消費品牌,打造社群消費循環,探索近期最夯的元宇宙新玩法。 Potato Media執行長顏宏霖表示,在CBMP計畫協助下,加上站內Web3.0資源,將快速協助雲林縣當地品牌升級轉型,幫助店家創造品牌價值,包含黑矸仔醬油、四代目麥芽酥、玉津烘焙坊、禪屋米胖工坊、YuDS沐耳飲、莫蒂精品巧克力、維野納複合式餐飲、頂雲咖啡、媽祖埔豆腐張、玉山碾米廠等,另外嘉義市麥麵、名香茗茶也等不及跨縣市加入,結合Potato Media站內活動,打造雲林專屬限定NFT道具與頭框,發行雲林扭蛋,體驗全新元宇宙新世界。 左起雲林縣計畫處處長李明岳、果俐文創執行長-陳郁涵、雲林縣議員周秀月、中華電信雲林營運處總經理張肇家、Potato Media執行長顏宏霖、LINE禮物代表睿鼎數位、12CMTaiwan行銷總監楊涵柔。(圖/由Potato Media提供) 此次Potato Media平台合作內容是店家會員註冊活動:首次註冊可得100積分 + 一顆扭蛋,店家推薦文章介紹,可領取店家消費優惠券,站內扭蛋禮物抽獎活動,獎項豐富:雲林限定禮品、雲林意象限定NFT道具與頭框,雲林幣扭一下APP政令大聲公獎勵活動,另外各種雲林美食伴手禮、住宿旅遊的店家,都可以使用行動支付或上LINE禮物平台實際體驗消費。 推薦評價好的 iphone維修 中心 擁有專業的維修技術團隊,同時聘請資深iphone手機維修專家,現場說明手機問題,快速修理,沒修好不收錢 產品缺大量曝光嗎?你需要的是一流 包裝設計 窩窩觸角包含自媒體、自有平台及其他國家營銷業務等,多角化經營並具有國際觀的永續理念。 雲林縣副縣長謝淑亞強調,此次計畫和Potato Media 合作,Potato Media 是一個在 2021 年 4 月正式發布的「區塊鏈 Web3.0 共享社群平台」,創作者和使用者都可以透過互動的機制,例如對文章點讚、留言與轉發分享,來獲取相對應比例的加密貨幣CFO(Potato Media 平台上的原生加密貨幣),跟Facebook、Instagram、YouTu...

要上網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷

台北網站設計      網頁設計公司     網站設計公司 食安五環為「源頭控管」、「重建生產管理履歷」、「提高查驗能力」、「加重生產者、廠商的責任」及「鼓勵、創造監督平臺」五大要環,除推動政府與市民消費者共同監督食品安全,更要從農場到餐桌,鏈結農村產業線,以網路社群為媒介,建立嘉義市農村網頁平台。活動現場介紹「農抵嘉」產銷網頁平台的內容,包含在地人文地產景,將景觀、產業、生態及文化等資訊整合、展現,更推廣在地農村農友優質、安全的農產品。要上「農抵嘉」網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷自己的農產品,嘉義市農友可以多利用,也提供店家採購管道。 「尚安心,農抵嘉」,透過「農抵嘉」產銷網頁平台,鏈結農村產業線並促進地產地消,從源頭管理食安,讓政府管理、民間參與,透過食安小教育,讓小朋友接觸農作物,與生產者互動,產生共鳴,一同攜手維護嘉義市的食安。記者會中也展示紅瓦厝社區所做的紅瓦窯烤,並有其他下埤花生等農產品,透過農場職人使「農特產品不只是農產品」,民眾可登入「農抵嘉」網頁http://chiayirural.com/index.asp瞭解更進一步的訊息。 網動廣告 參考資料:蕃新聞https://n.yam.com/Article/20171226529712 Orignal From: 要上網站行銷農產品,得經過市政府抽驗農藥殘留,檢驗合格才能上網行銷

IEA:疫情衝擊能源需求 但再生能源呈創紀錄成長_台中搬家公司

※ 台中搬家公司 教你幾個打包小技巧,輕鬆整理裝箱! 還在煩惱搬家費用要多少哪?台中大展搬家線上試算搬家費用,從此不再擔心「物品怎麼計費」、「多少車才能裝完」 摘錄自2020年11月10日中央社報導 國際能源總署(IEA)報告今天(10日)指出,武漢肺炎(COVID-19)疫情可能衝擊能源需求,但電力部門再生能源繼續以創紀錄速度成長。 IEA執行董事比羅爾(Fatih Birol)表示:「在2025年,再生能源將成為全球最大發電來源,預計將提供1/3的全球電力,終結煤炭50年來作為最大電力供應來源的地位。」 ※推薦 台中搬家公司 優質服務,可到府估價 台中搬鋼琴,台中金庫搬運,中部廢棄物處理,南投縣搬家公司,好幫手搬家,西屯區搬家 IEA關於再生能源的年度報告估計,儘管受到疫情干擾,今年的再生能源新發電容量可望創紀錄,達將近200GW(GW為十億瓦)。 能源轉型 國際新聞 再生能源 疫情看氣候與能源 本站聲明:網站內容來源環境資訊中心https://e-info.org.tw/,如有侵權,請聯繫我們,我們將及時處理 ※ 台中搬家公司 教你幾個打包小技巧,輕鬆整理裝箱! 還在煩惱搬家費用要多少哪?台中大展搬家線上試算搬家費用,從此不再擔心「物品怎麼計費」、「多少車才能裝完」 Orignal From: IEA:疫情衝擊能源需求 但再生能源呈創紀錄成長_台中搬家公司