2015-09-28 160 views
0
for x,y in my_dict.iteritems(): 
    for z in y: 
      def done_callback(result): 

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


      try: 
        pool.apply_async(function_returns_tuple,(x,z,my_val),done_callback) 
      except Exception as e: 
        print e 

当我看到new_content的值时,它是空的,也是回调函数 - done_callback没有被调用。我错过了某些部分?回调没有被调用

+0

“当我看到new_content的值”在代码中从不显示,并且与问题相关。但它看起来像典型的异步问题。记住 - 任何来自异步的结果都应该只能从回调中访问(或者回调位于堆栈跟踪中的某个地方)。你可能会喜欢使用'concurrent.futures.ThreadPoolExecutor'来为你管理异步。 – Amadan

+0

new_content只是一个列表,除了所有for循环以外,我都在这些列表之外进行检查。 – user3089927

+0

然后它就像我预测的那样。假设你有四个孩子,你告诉他们:“我需要去工作,但是我的手机丢失了,所以每个人都会搜索,当你找到它的时候把它给我!”然后,而不是等待,*你马上去工作*。你的一个孩子找到了电话,然后试图把它给你,但你不在那里了。与此同时,你在工作,无电话,想知道为什么孩子们这些日子这么懒。 – Amadan

回答

0

这里是一个工作小例子:

from multiprocessing import Pool 
from time import sleep 

my_dict = { "a": [1, 2], "b": [3] } 
my_val = 5 

# has to be defined before Pool is created 
def processing_function(args): 
    (x, y, v) = args  # mapped function only gets one arg; so we unpack 
    if y == 2:   # we throw a wrinkle in, 
     return ('', '') # to demonstrate filter 
    return ("[Code %s %d %d]" % (x, y, v), "[Content %s %d %d]" % (x, y, v)) 


pool = Pool(2) # execute two workers in parallel (feel free to change) 

# make an iterator for all your values 
inputs = ((x, z, my_val) for (x, y) in my_dict.iteritems() for z in y) 
async_results = pool.map_async(processing_function, inputs) 
pool.close()  # necessary before pool.join() 
pool.join()  # wait for all processes in the pool to finish 
results = async_results.get() # now we can get the results 
# we can extract just the results we want... 
non_empty_content_joined = ''.join(
     content for (code, content) in results if content != '') 
print non_empty_content_joined 
# => [Content a 1 5][Content b 3 5] 
+0

感谢这个例子,但是我的代码中缺少哪部分内容。请您在我的摘录中指出循环漏洞? – user3089927

+0

如果在主线程中需要它们,'join()'将等待主线程中的结果。 – Amadan

0

当你指定apply_async一个回调函数,回调将在一段时间后调用。 “异步”部分意味着您可以在apply的工作完成之前继续在当前线程上处理您的业务。

在您的示例代码中,您正在循环中调用apply_async,但您并未等待任何操作完成。如果要等待操作完成,则必须保留主线程(例如,通过阻止或循环)。