具有动态数据输入的多线程功能

时间:2016-02-15 12:03:50

标签: python multithreading multiprocessing

我使用this answerthis blog post中讨论的设计模式实现多线程功能。

我的数据源是动态的(来自Web 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() 

1 个答案:

答案 0 :(得分:1)

我认为,非静态是指在工人已经消耗它们的同时产生其物品的来源。在这种情况下,您可以使用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()调用的返回值的iterable。