具有动态数据输入的多线程功能
Multithreaded functionality with dynamic data input
我正在使用 this answer and this blog post 中讨论的设计模式实现多线程功能。
我的数据源是动态的(来自网络 POST),但我能找到的所有示例都使用静态数据源。
因此我的问题是:如何使用非静态数据输入源实现多线程功能?
示例代码:
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 并传递生成器而不是准备好的列表。
import multiprocessing.dummy
import threading
def generate():
for i in range(20):
print('generating {}'.format(i))
yield i
def consume(i):
print('thread {} consuming {}'.format(threading.current_thread().ident, i))
pool = multiprocessing.dummy.Pool(4)
list(pool.imap(consume, generate()))
注意实际消耗作为 Pool.imap()
调用的 return 值的可迭代对象。
我正在使用 this answer and this blog post 中讨论的设计模式实现多线程功能。
我的数据源是动态的(来自网络 POST),但我能找到的所有示例都使用静态数据源。
因此我的问题是:如何使用非静态数据输入源实现多线程功能?
示例代码:
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 并传递生成器而不是准备好的列表。
import multiprocessing.dummy
import threading
def generate():
for i in range(20):
print('generating {}'.format(i))
yield i
def consume(i):
print('thread {} consuming {}'.format(threading.current_thread().ident, i))
pool = multiprocessing.dummy.Pool(4)
list(pool.imap(consume, generate()))
注意实际消耗作为 Pool.imap()
调用的 return 值的可迭代对象。