2011-03-17 64 views

回答

3

而现在,对于一些替代性的乐趣:)

import threading 
from itertools import repeat 
from multiprocessing.pool import ThreadPool # this is a THREAD POOL! undocumented :) 


def execute_me(): 
    print threading.current_thread().name, 'python is fun' 


tp = ThreadPool(processes=4) 
print tp.map(lambda x: x(), repeat(execute_me, 4)) 

输出:

% python mpthreadpool.py 
Thread-1 python is fun 
Thread-2 python is fun 
Thread-3 python is fun 
Thread-3 python is fun 
[None, None, None, None] 
0
for t in threadpool: 
    t.execute(function) 
+0

N次进来? – 2011-03-17 18:23:15

+0

当你创建线程池 – theheadofabroom 2011-03-17 18:26:33

+1

@BiggAl @fabrizio Python没有内置线程池的概念,所以没有额外的信息,这不是一个有用的答案 – 2011-03-17 18:32:58

1
threads = [] 
for i in range(NUM_THREADS): 
    t = threading.Thread(target=your_function, args=your_argslist) 
    t.start() # if you want to start it immediately, otherwise you can defer it 
    threads.append(t) 
+0

OP询问了一个模型,而不是一个实现。如果您经常添加和删除对象,您也可以考虑使用deque。 – theheadofabroom 2011-03-17 18:53:28

1

的Python的问题是,它不支持,因为基于操作系统的线程着名的GIL(见http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/)。在我看来,使用真正线程的最简单的方法(例如n个线程)是使用并行python(请参阅http://www.parallelpython.com/)与并行python版本的并行映射(http://honeypot.net/yet-another-python-地图)。这可以使用如下:

def func(arg1): 
    # do something with arg1 
    return result 

import pp 
import ppmap 

ppmap.ppmap(n, func, [test1, ... test2]) 
+0

但在python中的线程不是作为一个轻量级进程的,而是一个逻辑线程。您可以将重量级线程(即进程)用于真正的cuncurrency,但不会共享状态。原因在于,在其他语言中,这种中间立场经常被看作是万灵丹,被滥用,然后被选为所有错误的来源。 – theheadofabroom 2011-03-17 20:07:55