如何启动最多X个线程?Python

vc9ivgsu  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(141)

您好,我有以下问题:
我的目标是提交一封电子邮件到一个在线列表。我有它的方式,现在开始尽可能多的线程作为电子邮件在我的01.csv文件,但我希望它有一个最大的10个线程,一旦1个线程完成继续与下一个,但从来没有超过10个活动线程。
这是我的主函数,它从csv中获取电子邮件并启动目标函数:

def main():
    get_emails()

    log("Starting tasks", "yellow")

    # Loop through users
    for user in users:
        # Start thread for each user

        # Random timer so everyone doesn't request at the same time
        #timer = random.randint(0, 100)/100
        #time.sleep(timer)

        thread = threading.Thread(target=targetfunc, args=(users[user], ))
        thread.start()

        
    #os.system("clear")

    log("Task started successfully!", "success")

这是获取邮件的函数:

def get_emails():
global users

with open("./emails.csv", "r") as f:
    data = csv.reader(f)
    
    for i, d in enumerate(data):
        if i == 0:
            data_titles = d
        else:
            users[d[0]] = {}

            for title in data_titles:
                users[d[0]][title] = d[data_titles.index(title)]

下面是targetfunc,电子邮件会提交该函数:

def targetfunc(data):
    global users_done
    global successCount
    #session = requests.session()

    email = data["EMAIL"]
...
...
...

我如何将这段代码变成一次只运行5个线程的代码?

eaf3rand

eaf3rand1#

您可以实现自己的队列并启动10个线程,每个线程都从队列中拉取,或者-对于这个简单的任务-您也可以使用具有给定数量工作线程的ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=10) as ex:
    for user in users:
        ex.submit(targetfunc, (users[user], ))

相关问题