如何使用线程池来执行无限循环功能?

Fen*_* Yu 7 python multithreading

我想做一个无限循环函数.

这是我的代码

def do_request():
    # my code here
    print(result)

while True:
    do_request()
Run Code Online (Sandbox Code Playgroud)

当使用while True它时,它有点慢,所以我想使用一个线程池来同时执行该函数do_request().这该怎么做 ?

就像使用ab(Apache Bench)来测试HTTP服务器一样.

Fen*_* Yu 1

最后,我解决了这个问题。我使用一个变量来限制线程数。

这是我的最终代码,解决了我的问题。

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)
Run Code Online (Sandbox Code Playgroud)

感谢您的所有回复。