是否有多线程map()函数?

San*_*dro 13 python multithreading

我有一个副作用免费的功能.我想为数组中的每个元素运行它,并返回一个包含所有结果的数组.

Python有什么东西可以生成所有值吗?

sam*_*gar 16

尝试多处理中的Pool.map函数:

http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers

它本身并不是多线程的,但实际上这很好,因为GIL会在Python中严重削弱多线程.


小智 5

在 Python 标准库中尝试concurrent.futures.ThreadPoolExecutor.map(3.2 版中的新功能)。

类似于map(func, *iterables)除了:

  • 可迭代对象被立即收集而不是懒惰地收集;
  • func 是异步执行的,并且可以同时进行多次对 func 的调用。

一个简单的例子(修改自ThreadPoolExecutor Example):

import concurrent.futures
import urllib.request

URLS = [
  'http://www.foxnews.com/',
  'http://www.cnn.com/',
  'http://europe.wsj.com/',
  'http://www.bbc.co.uk/',
]

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    # Do something here
    # For example
    with urllib.request.urlopen(url, timeout=timeout) as conn:
      try:
        data = conn.read()
      except Exception as e:
        # You may need a better error handler.
        return b''
      else:
        return data

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
    # map
    l = list(executor.map(lambda url: load_url(url, 60), URLS))

print('Done.')
Run Code Online (Sandbox Code Playgroud)