我有一个函数需要被调用N次。我想T线程并行地执行这个函数。你将如何在Python中建模?Python线程在计数器上
回答
而现在,对于一些替代性的乐趣:)
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]
for t in threadpool:
t.execute(function)
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)
OP询问了一个模型,而不是一个实现。如果您经常添加和删除对象,您也可以考虑使用deque。 – theheadofabroom 2011-03-17 18:53:28
的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])
但在python中的线程不是作为一个轻量级进程的,而是一个逻辑线程。您可以将重量级线程(即进程)用于真正的cuncurrency,但不会共享状态。原因在于,在其他语言中,这种中间立场经常被看作是万灵丹,被滥用,然后被选为所有错误的来源。 – theheadofabroom 2011-03-17 20:07:55
- 1. Python线程与计时器
- 2. 线程和新计数器
- 3. 线程计时器问题python
- 4. Python线程计时器问题
- 5. Python游戏计时器(线程?)
- 6. 加入python线程,总计
- 7. Python线程计时器运行函数与传递变量
- 8. 工作线程的线程计时器?
- 9. 上增加线程计数高延迟
- 10. 没有线程在Python中的计时器?
- 11. Java线程安全计数器
- 12. 当前线程的性能计数器
- 13. Reg:线程中的计数器变量
- 14. 使用线程计算Python程序
- 15. 线程之间的Jmeter线程组共享计数器
- 16. 线程在python
- 17. 线程在python
- 18. Django计时器线程
- 19. 计时器线程内
- 20. 线程上的Python Sounddevice.play()
- 21. 正在中止计时器线程
- 22. 在C#中使用计时器线程
- 23. 在新线程中的C#计时器
- 24. Python的线程定时器
- 25. Python线程无法在cygwin上运行
- 26. 线程在自定义线程上锁定python
- 27. 线程服务器套接字在python
- 28. 如何把TCP服务器上的另一个线程在python
- 29. 担心在Apache服务器上的python线程
- 30. Python的线程设计问题
N次进来? – 2011-03-17 18:23:15
当你创建线程池 – theheadofabroom 2011-03-17 18:26:33
@BiggAl @fabrizio Python没有内置线程池的概念,所以没有额外的信息,这不是一个有用的答案 – 2011-03-17 18:32:58