2013-04-11 208 views
4

背景
我有一個用於構建和執行Verilog-AMS tesbenches的Python腳本的集合。整體設計是在考慮到線程的情況下構建的,因爲每個主要的測試用例都是自己的測試平臺,並且每個實例都有獨立的所有支持文件/數據輸出。唯一的共享項目將是啓動腳本和我的數據提取腳本。我面臨的問題是我的Verilog-AMS模擬器本身不支持多線程,對於我的測試用例來說,它需要大量的時間才能完成。Python - 多線程/多處理

問題
我上運行該本機具有的RAM 32GiB和8個「核」供我使用,我或許可以用32來訪問一臺機器,我想利用可用的計算能力並同時執行模擬。最好的方法是什麼?

我目前使用subprocess.call來執行我的模擬。我想一次執行多達n的命令,每個命令在單獨的線程上執行/作爲一個單獨的進程執行。一旦模擬完成,隊列中的下一個(如果存在的話)將執行。

我對Python很新,並沒有真正寫過一個線程化的應用程序。我想就如何繼續進行一些建議。我看到this的問題,並且我認爲multiprocessing模塊可能更適合我的需求。

你們都推薦什麼?

回答

4

我過去在機器學習和數據挖掘方面做過類似的工作。在你的情況下使用multiprocessing可能不是那麼困難的任務。這取決於你對製作程序的熱衷程度,你可以使用Threaded Pool模式。我個人最喜歡的是Producer - 消費者模式使用Queue,這個設計可以處理各種複雜的任務。下面是使用multiprocessing樣本玩具程序:

import multiprocessing 
from multiprocessing import Queue, Process 
from Queue import Empty as QueueEmpty 

# Assuming this text is very very very very large 
text="Here I am writing some nonsense\nBut people will read\n..." 

def read(q): 
    """Read the text and put in a queue""" 
    for line in text.split("\n"): 
     q.put(line) 

def work(qi, qo): 
    """Put the line into the queue out""" 
    while True: 
     try: 
      data = qi.get(timeout = 1) # Timeout after 1 second 
      qo.put(data) 
     except QueueEmpty: 
      return # Exit when all work is done 
     except: 
      raise # Raise all other errors 

def join(q): 
    """Join all the output queue and write to a text file""" 
    f = open("file.txt", w) 
    while True: 
     try: 
      f.write(q.get(timeout=1)) 
     except QueueEmpty: 
      f.close() 
      return 
     except: 
      raise 

def main(): 
    # Input queue 
    qi = Queue() 
    # Output queue 
    qo = Queue() 
    # Start the producer 
    Process(target = read, args = (qi,)).start() 
    # Start 8 consumers 
    for i in range(8): 
     Process(target = work, args = (qi, qo,)).start() 
    # Final process to handle the queue out 
    Process(target = join, args = (qo,)).start() 

本型從內存所以如果有任何錯誤,請指正。 :)

+1

謝謝,這有助於。你是否知道在使用'subprocess.call'執行外部命令時這會很好地發揮作用,這樣隊列中的每個項目都需要執行一個外部命令,例如, 'program_name.exe -arguments' – TehTechGuy 2013-04-12 16:49:07

+1

我還沒有嘗試結合'subprocess'和'multiprocessing';然而,只要你正確處理'subprocess'中的通信,我不認爲這會是一個問題。我已經看到在[這個問題]中使用兩個實現(http://stackoverflow.com/questions/884650/how-to-spawn-parallel-child-processes-on-a-multi-processor-system)。這看起來像你在找什麼。 – nqngo 2013-04-13 06:27:25

+0

謝謝,這有助於很多!我認爲你的帖子和那一個之間,我應該都設置:) – TehTechGuy 2013-04-13 14:57:47