我使用this answer和this blog post中讨论的设计模式实现多线程功能。你知道吗
我的数据源是动态的(来自web文章),但我能找到的所有示例都使用静态数据源。你知道吗
因此,我的问题是:如何使用非静态数据输入源实现多线程功能?
示例代码:
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
# This is a static data source. I need it to be dynamic!
urls = [
'http://www.python.org',
'http://www.python.org/about/',
# etc..
]
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join()
我想,非静态的意思是,当工人已经在消费项目时,生产它的项目的源。在这种情况下,您可以使用
Pool.imap()
API传递生成器,而不是准备好的列表。你知道吗注意实际使用iterable,它是
Pool.imap()
调用的返回值。你知道吗相关问题 更多 >
编程相关推荐