Python併發編程之concurrent.futures

    concurrent.futures模塊提供了一個異步執行callables的高級接口。 可使用ThreadPoolExecutor和ProcessPoolExecutor。 二者都繼承了相同的接口,該接口由抽象的Executor類定義。dom

    一個抽象類,提供異步執行調用的方法。 它不該該直接使用,而是經過其具體的子類。異步

    submit (fn*args**kwargs):提交執行的函數並獲取一個Future對象,例如:函數

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())

    ThreadPoolExecutor:是Executor子類,它使用一個線程池來異步執行調用。concurrent.futures.ThreadPoolExecutor(max_workers=Nonethread_name_prefix=''initializer=Noneinitargs=())。例如:url

import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

    ProcessPoolExecutor:concurrent.futures.ProcessPoolExecutor(max_workers=Nonemp_context=Noneinitializer=Noneinitargs=()):使用以下:線程

import concurrent.futures
import math
executor = ProcessPoolExecutor(max_workers=5)

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    for i in range(10):
        future = executor.submit(is_prime, n)

if __name__ == '__main__':
    main()

    Future: Future類封裝了可調用的異步執行。 該實例由Executor.submit()建立。code

相關文章
相關標籤/搜索