我想做一个无限循环函数。
这是我的代码
def do_request():
# my code here
print(result)
while True:
do_request()
使用while True
执行此操作时,它有点慢,所以我想使用线程池同时执行函数do_request()
。怎么做?
就像使用ab
(Apache Bench)测试HTTP服务器一样。
答案 0 :(得分:0)
您可以在Python中使用threading来实现此目的。 可以是类似的东西(当仅使用两个额外的线程时):
import threading
# define threads
task1 = threading.Thread(target = do_request)
task2 = threading.Thread(target = do_request)
# start both threads
task1.start()
task2.start()
# wait for threads to complete
task1.join()
task2.join()
基本上,你可以根据需要启动尽可能多的线程(确保你没有太多,所以你的系统可以处理它),然后你.join()
等待任务完成。< / p>
或者你可以使用multiprocessing Python模块获得更多的爱好。
答案 1 :(得分:0)
请尝试以下代码:
import multiprocessing as mp
import time
def do_request():
while(True):
print('I\'m making requests')
time.sleep(0.5)
p = mp.Process(target=do_request)
p.start()
for ii in range(10):
print 'I\'m also doing other things though'
time.sleep(0.7)
print 'Now it is time to kill the service thread'
p.terminate()
主线程处理一个执行请求的服务线程并继续执行,然后它完成服务线程。
答案 2 :(得分:0)
也许您可以使用concurrent.futures.ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
import time
def wait_on_b(hello):
time.sleep(1)
print(hello) # b will never complete because it is waiting on a.
return 5
def wait_on_a():
time.sleep(1)
print(a.result()) # a will never complete because it is waiting on b.
return 6
executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b, 3)
b = executor.submit(wait_on_a)
答案 3 :(得分:0)
这个怎么样?
from threading import Thread, Event
class WorkerThread(Thread):
def __init__(self, logger, func):
Thread.__init__(self)
self.stop_event = Event()
self.logger = logger
self.func = func
def run(self):
self.logger("Going to start the infinite loop...")
#Your code
self.func()
concur_task = WorkerThread(logger, func = do_request)
concur_task.start()
结束这个帖子......
concur_task.stop_event.set()
concur_task.join(10) #or any value you like
答案 4 :(得分:0)
最后,我已经解决了这个问题。我使用变量来限制线程数。
这是我的最终代码,解决了我的问题。
import threading
import time
thread_num = 0
lock = threading.Lock()
def do_request():
global thread_num
# -------------
# my code here
# -------------
with lock:
thread_num -= 1
while True:
if thread_num <= 50:
with lock:
thread_num += 1
t = threading.Thread(target=do_request)
t.start()
else:
time.sleep(0.01)
感谢所有回复。