2009-12-01 31 views
0

我遇到一些問題,從功能列表啓動線程。它們在列表中,因爲它們是配置特定的功能。我正在包裝這些函數,以便我可以將函數的結果存儲在'self'中,但是以非線程安全的方式出現錯誤,從而得到正確數量的線程,但是有些情況並不正確功能。下面是示例代碼:不正確的函數被調用的多個快速調用python的threading.Thread()

import threading, time 

class runParallelTest(): 
    def __init__(self): 
     pass 

    def runList(self, functionList): 
     threadList = [] 
     for functionListIndex in range(0, len(functionList)): 
      newThread = threading.Thread(target=lambda:self._run_parallel_job(functionList[functionListIndex])) 
      newThread.start() 
      threadList.append(newThread) 
      # sleep delay that makes it all work fine. 
      #time.sleep(2) 

     # We wait for all the threads to complete and if any of them 
     # doesn't we report a failure. 
     for thread in threadList: 
      thread.join(3600*24) # 1 day better be enough 
      if thread.isAlive() == True: 
       raise Exception("thread.isAlive==True") 

    def _run_parallel_job(self, function): 
     results = function() 
     # store the results in a threadsafe way in self 
     # (I promise I'm using semaphores) 

def f(x): 
    print "f(%d) run" % x 
    return x 

if __name__ == '__main__': 
    rp = runParallelTest() 

    functionList = [ 
     lambda:f(0), 
     lambda:f(1), 
     lambda:f(2), 
     lambda:f(3), 
     lambda:f(4), 
     lambda:f(5), 
     lambda:f(6), 
     lambda:f(7), 
     ] 

    rp.runList(functionList) 

當我跑,我看到這樣的事情:

> python thread_problem.py 
f(0) run 
f(1) run 
f(2) run 
f(4) run 
f(5) run 
f(5) run 
f(6) run 
f(7) run 
> 

雖然我在打印預期不同的順序,我想我應該看到數字0-7,沒有重複,但我不知道。如果我添加time.sleep(2),問題會奇蹟般地消失,但我真的很想明白爲什麼它不按我認爲的方式工作。

非常感謝!

回答

1

問題是functionList[functionListIndex]只有在lambda處於運行狀態(在線程內)時才被評估。屆時,functionListIndex的值可以改變。

爲了解決這個問題,你可以傳遞一個參數,將在定義時進行評估的拉姆達:

newThread = threading.Thread(target=lambda func=functionList[functionListIndex]: self._run_parallel_job(func)) 

由於默認參數值函數在定義時評價,這將工作。

一個更Python的解決方案是避免拉姆達並使用args參數:

newThread = threading.Thread(target=self._run_parallel_job, args=(functionList[functionListIndex],)) 
+0

啊!現在我明白了。謝謝您的幫助。 – 2009-12-01 19:27:19

相關問題