gpt4 book ai didi

python - Python 2.7 中的多线程

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:22 24 4
gpt4 key购买 nike

我不确定如何进行多线程处理,在阅读了一些 stackoverflow 的答案后,我想到了这个。注:Python 2.7

from multiprocessing.pool import ThreadPool as Pool
pool_size=10
pool=Pool(pool_size)

for region, directory_ids in direct_dict.iteritems():
for dir in directory_ids:
try:
async_result=pool.apply_async(describe_with_directory_workspaces, (region, dir, username))
result=async_result.get()
code=result[0]
content=result[1]
except Exception as e:
print "Some error happening"
print e

if code==0:
if content:
new_content.append(content)
else:
pass
else:
return error_html(environ, start_response, content)

我在这里尝试做的是使用不同的区域和目录参数调用 describe_with_directory_workspaces 并并行运行它,以便我在新内容中快速获取数据。目前,它是串联的,这给最终用户带来了缓慢的性能。

我做的对吗?或者有更好的方法吗?我如何才能确认我正在按预期运行多线程?

最佳答案

在将所有作业排入队列之前,不要调用 async_result.get,否则一次只能运行一个作业。

尝试先对所有作业进行排队,然后在所有结果都排队后处理每个结果。像这样的东西:

results = []
for region, directory_ids in direct_dict.iteritems():
for dir in directory_ids:
result = pool.apply_async(describe_with_directory_workspaces,
(region, dir, username))
results.append(result)

for result in results:
code, content = result.get()
if code == 0:
# ...

如果您想在异步回调中处理结果,您可以向 pool.apply_async 提供一个回调参数,如文档中所述 here :

for region, directory_ids in direct_dict.iteritems():
for dir in directory_ids:
def done_callback(result):
pass # process result...

pool.apply_async(describe_with_directory_workspaces,
(region, dir, username),
done_callback)

关于python - Python 2.7 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com