2015-09-28 154 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,但您並未等待任何操作完成。如果要等待操作完成,則必須保留主線程(例如,通過阻止或循環)。