![](/img/trans.png)
[英]How do I handle multiple requests to python program using zeromq and threading or async?
[英]How do I use the threading module in python to handle simultaneous http requests?
我有一些代碼為它處理的每個項目對 api 進行兩次調用。 它按預期工作,但每個項目需要 1-3 秒。 為了加快速度,我嘗試使用線程模塊一次執行 10 個請求,但它的行為似乎與添加線程之前相同。 每次調用處理來自 api 的數據所需的時間約為 0.2 毫秒,因此不應導致阻塞。
這是我的代碼的相關部分:
import threading
.
.
.
def secondary():
global queue
item = queue.pop()
queue|=func1(item)# func1 returns data from an api using the requests module
with open('data/'+item,'w+') as f:
f.write(func2(item))# func2 also returns data from an api using the requests module
global num_procs
num_procs-=1
def primary():
t=[]# threads
global num_procs
num_procs+=min(len(queue),10-num_procs)
for i in range(min(len(queue),10-num_procs)):
t+=[threading.Thread(target=secondary)]
for i in t:
i.start()
i.join()
queue = {'initial_data'}
num_procs=0# number of currently running processes - when it reaches 10, stop creating new ones
while num_procs or len(queue):
primary()
我需要做什么才能使其同時運行? 我寧願使用線程,但如果異步更好,我該如何實現呢?
啟動每個線程后,立即等待線程完成:
for i in t:
i.start()
i.join()
線程永遠沒有機會並行執行。 相反,僅在您啟動所有線程后等待線程完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.