Twisted同时执行10个线程并等待resu

2024-05-20 19:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个验证电子邮件语法和MX记录列表的程序,由于阻塞编程非常耗时,我想进行异步或按线程,这是我的代码:

with open(file_path) as f:
    # check the status of file, if away then file pointer will be at the last index
    if (importState.status == ImportStateFile.STATUS_AWAY):
        f.seek(importState.fileIndex, 0)

    while True:
        # the number of emails to process is configurable 10 or 20
        emails = list(islice(f, app.config['NUMBER_EMAILS_TO_PROCESS']))
        if len(emails) == 0:
            break;

        importState.fileIndex = importState.fileIndex + len(''.join(emails))

        for email in emails:
            email = email.strip('''<>;,'\r\n ''').lower()
            d = threads.deferToThread(check_email, email)
            d.addCallback(save_email_status, email, importState)

        # set the number of emails processed 
        yield set_nbrs_emails_process(importState)

        # do an insert of all emails
        yield reactor.callFromThread(db.session.commit)

# set file status as success
yield finalize_import_file_state(importState)
reactor.callFromThread(reactor.stop)

检查电子邮件功能:

^{pr2}$

我需要的是在同一时间处理10封电子邮件,然后等待结果。在


Tags: oftheif电子邮件emailcheckasstatus
1条回答
网友
1楼 · 发布于 2024-05-20 19:54:47

我不知道为什么示例代码中会涉及线程。你不需要线程与Twisted的电子邮件交互,也不需要同时这样做。在

如果有一个异步函数返回Deferred,那么只需调用它十次,十个不同的工作流将并行进行:

for i in range(10):
    async_check_email_returning_deferred()

如果您想知道何时所有10个结果都可用,可以使用gatherResults:

^{pr2}$

all_results是一个Deferred,当email_results中的所有Deferreds都已触发时(或当其中的第一个用Failure触发)时将触发。在

相关问题 更多 >