2013-04-11 212 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