Skip to main content
 首页 » 编程设计

python之Python 2.7 中的多线程

2024年08月25日31qlqwjy

我不确定如何进行多线程处理,在阅读了一些 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)