【发布时间】:2015-09-21 21:13:03
【问题描述】:
我不确定如何进行多线程处理,在阅读了一些 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 并并行运行它,以便我在新内容中快速获取数据。目前,它正在串联,这给最终用户带来了缓慢的性能。
我做得对吗?或者有什么更好的方法吗?我如何确认我正在按预期运行多线程?
【问题讨论】:
-
您尝试的解决方案中存在多个可能的问题(代码是串行的,您似乎是在 Web 请求中创建一个新的线程池)。而是从实际问题开始:它是否是 wsgi 应用程序的一部分(由
error_html(..)判断)?describe_with_..()函数有什么作用(是否受 IO 限制)?您是否考虑过在不等待结果完成请求的情况下将任务卸载到后台线程/进程中?
标签: python multithreading python-2.7