[英]Twisted execute 10 threads in same time and wait for result
编写一个程序来验证电子邮件语法和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)
查看电子邮件功能:
def check_email(email):
pipe = subprocess.Popen(["./check_email", '--email=%s' % email], stdout=subprocess.PIPE)
status = pipe.stdout.read()
try:
status = int(status)
except ValueError:
status = -1
return status
我需要的是同时处理10封电子邮件,然后等待结果。
我不确定为什么示例代码中涉及线程。 您不需要线程来与Twisted进行电子邮件交互,也不需要同时进行。
如果您有一个异步函数返回Deferred
,则可以只调用它十次,并且十个不同的工作流将并行进行:
for i in range(10):
async_check_email_returning_deferred()
如果您想知道所有十个结果何时可用,可以使用collectResults:
from twisted.internet.defer import gatherResults
...
email_results = []
for i in range(10):
email_results.append(async_check_mail_returning_deferred())
all_results = gatherResults(email_results)
all_results
是Deferred
当所有的,将火Deferreds
在email_results
已经解雇(或当他们的第一个触发Failure
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.