2014-10-05 13 views
-2

如果我有一个应用程序或函数(不能拆分),它使用多线程时速度更快,并且在使用多处理时工作更快,如何在每个进程中启动多个线程?Python:是否有任何意义使用多处理和线程(对于相同的任务)?

编辑:

我想这是可能的,像这样的代码:

class ThreadClass(threading.Thread): 
    def __init__(self, threads_in_queue, worker_function, *args, **kwargs): 
     super().__init__() 
     ... 
    def run(self): # метод должен быть. 
     while True: 
      ... 
      q = self.threads_in_queue.get() 
      self.worker_function(q) 

threads_in_queue = multiprocessing.JoinableQueue(maxsize=number_of_threads) 

class ProcessClass(...): 
    def __init__(self, processes_in_queue): 
     ... 

    def run(self): 
     while True: 
      ... 
      q = self.processes_in_queue.get() 
      threads_in_queue.put(q) 

def worker_function(...): 
    ... 

for i in number_of_threads: 
    t = ThreadClass(worker_function, threads_in_queue, arg1, ..., kwarg1=..., ...) 
    t.setDaemon(True) 
    t.start() 

if __name__ == '__main__': 

    processes_in_queue = multiprocessing.JoinableQueue() 

    for i in number_of_processes: 
     t = ProcessClass(processes_in_queue) 
     t.daemon = True 
     t.start() 

    for thing_to_queue in things_to_queue: 
     processes_in_queue.put(...) 

回答

1

是的,这是可能的,你可以用同一个程序既多且多线程;尽管这可能不常见。由于默认Python具有全局解释器锁,因此可以使用多处理来饱和多个CPU或内核,但是如果您正在执行一些也涉及大量阻塞I/O的主要任务,那么可以使用线程来增加总并行度并减少延迟。

例如,假设您正在编写某种类型的并行爬网程序。在Python中解析HTML实际上是CPU密集型的,但是抓取主要是网络和I/O绑定。因此,您可能会使用多处理功能同时在不同的进程中分配多个并行搜寻器,但随后会在该进程中使用线程,以增加您处理的并行连接的总数。

可能还有其他例子,将两者结合起来会有用。但是,通常当我编写与以前类似的系统时,我并没有直接使用built-in Python multiprocessing library,而是在同一台机器上完全分离了不同的进程,然后通过gevent库(这是一种形式多线程)来增加并行性。我已经为多个Web服务完成了这项工作,其中每个进程都是在单独的端口上提供请求,然后直接在所有进程中拥有某种形式的负载平衡器点。这是一个非常可扩展的架构。

值得一提的是,Python多线程库,Python线程库和gevent库在它们的界面中几乎完全相同,因此您可以在它们之间无缝切换。

相关问题