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

2024-04-25 18:09:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用this answerthis 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() 

Tags: thetoorgimport功能http示例www
1条回答
网友
1楼 · 发布于 2024-04-25 18:09:18

我想,非静态的意思是,当工人已经在消费项目时,生产它的项目的源。在这种情况下,您可以使用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()))

注意实际使用iterable,它是Pool.imap()调用的返回值。你知道吗

相关问题 更多 >