concurrent.futures — Launching parallel tasks — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Паралельне виконання » concurrent.futures — Launching parallel tasks | Theme | concurrent.futures — Launching parallel tasks ¶ Added in version 3.2. Source code: Lib/concurrent/futures/thread.py , Lib/concurrent/futures/process.py , and Lib/concurrent/futures/interpreter.py The concurrent.futures module provides a high-level interface for asynchronously executing callables.
The asynchronous execution can be performed with threads, using ThreadPoolExecutor or InterpreterPoolExecutor , or separate processes, using ProcessPoolExecutor . Each implements the same interface, which is defined by the abstract Executor class. concurrent.futures.Future must not be confused with asyncio.Future , which is designed for use with asyncio tasks and coroutines. See the asyncio’s Future documentation for a detailed comparison of the two.
Availability : not WASI. This module does not work or is not available on WebAssembly. See WebAssembly platforms for more information. Об’єкти виконавця ¶ class concurrent.futures. Executor ¶ Абстрактний клас, який надає методи для асинхронного виконання викликів. Його слід використовувати не безпосередньо, а через його конкретні підкласи. submit ( fn , / , * args , ** kwargs ) ¶ Планує виконання викликаного, fn , як fn(*args, **kwargs) і повертає об’єкт Future , який представляє виконання викликаного. with ThreadPoolExecutor ( max_workers = 1 ) as executor : future = executor . submit ( pow , 323 , 1235 ) print ( future . result ()) map ( fn , * iterables , timeout = None , chunksize = 1 , buffersize = None ) ¶ Similar to map(fn, *iterables) except: The iterables are collected immediately rather than lazily, unless a buffersize is specified to limit the number of submitted tasks whose results have not yet been yielded.
If the buffer is full, iteration over the iterables pauses until a result is yielded from the buffer. fn is executed asynchronously and several calls to fn may be made concurrently. The returned iterator raises a TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to Executor.map() . timeout can be an int or a float. If timeout is not specified or None , there is no limit to the wait time.
If a fn call raises an exception, then that exception will be raised when its value is retrieved from the iterator. When using ProcessPoolExecutor , this method chops iterables into a number of chunks which it submits to the pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer. For very long iterables, using a large value for chunksize can significantly improve performance compared to the default size of 1.
With ThreadPoolExecutor and InterpreterPoolExecutor , chunksize has no effect. Змінено в версії 3.5: Added the chunksize parameter. Змінено в версії 3.14: Added the buffersize parameter. shutdown ( wait = True , * , cancel_futures = False ) ¶ Дайте сигнал виконавцю, що він повинен звільнити будь-які ресурси, які він використовує, коли завершено виконання поточних ф’ючерсів.
Виклики Executor.submit() і Executor.map() , здійснені після вимкнення, викличуть RuntimeError . Якщо wait має значення True , тоді цей метод не повернеться, доки не буде завершено виконання всіх очікуваних ф’ючерсів і не буде звільнено ресурси, пов’язані з виконавцем.
Якщо wait має значення False , тоді цей метод повернеться негайно, а ресурси, пов’язані з виконавцем, будуть звільнені, коли завершиться виконання всіх очікуваних ф’ючерсів. Незалежно від значення wait , уся програма Python не завершить роботу, доки не буде завершено виконання всіх незавершених ф’ючерсів.
Якщо cancel_futures має значення True , цей метод скасує всі незавершені ф’ючерси, які виконавець ще не запускав. Будь-які завершені або запущені ф’ючерси не будуть скасовані, незалежно від значення cancel_futures . Якщо і cancel_futures , і wait мають значення True , усі ф’ючерси, які почав виконувати виконавець, будуть завершені до повернення цього методу.
Решта ф’ючерсів скасовано. You can avoid having to call this method explicitly if you use the executor as a context manager via the with statement, which will shutdown the Executor (waiting as if Executor.shutdown() were called with wait set to True ): import shutil with ThreadPoolExecutor ( max_workers = 4 ) as e : e . submit ( shutil . copy , 'src1.txt' , 'dest1.txt' ) e . submit ( shutil . copy , 'src2.txt' , 'dest2.txt' ) e . submit ( shutil . copy , 'src3.txt' , 'dest3.txt' ) e . submit ( shutil . copy , 'src4.txt' , 'dest4.txt' ) Змінено в версії 3.9: Added the cancel_futures parameter.
ThreadPoolExecutor ¶ ThreadPoolExecutor — це підклас Executor , який використовує пул потоків для асинхронного виконання викликів. Взаємоблокування можуть виникати, коли виклик, пов’язаний із Future , чекає результатів іншого Future . Наприклад: import time def wait_on_b (): time . sleep ( 5 ) print ( b . result ()) # b will never complete because it is waiting on a. return 5 def wait_on_a (): time . sleep ( 5 ) print ( a . result ()) # a will never complete because it is waiting on b. return 6 executor = ThreadPoolExecutor ( max_workers = 2 ) a = executor . submit ( wait_on_b ) b = executor . submit ( wait_on_a ) І: def wait_on_future (): f = executor . submit ( pow , 5 , 2 ) # This will never complete because there is only one worker thread and # it is executing this function. print ( f . result ()) executor = ThreadPoolExecutor ( max_workers = 1 ) future = executor . submit ( wait_on_future ) # Note: calling future.result() would also cause a deadlock because # the single worker thread is already waiting for wait_on_future(). class concurrent.futures.
ThreadPoolExecutor ( max_workers = None , thread_name_prefix = '' , initializer = None , initargs = () , ** ctxkwargs ) ¶ Підклас Executor , який використовує пул щонайбільше max_workers потоків для асинхронного виконання викликів. All threads enqueued to ThreadPoolExecutor will be joined before the interpreter can exit. Note that the exit handler which does this is executed before any exit handlers added using atexit .
This means exceptions in the main thread must be caught and handled in order to signal threads to exit gracefully. For this reason, it is recommended that ThreadPoolExecutor not be used for long-running tasks. initializer — необов’язковий виклик, який викликається на початку кожного робочого потоку; initargs — це кортеж �
The rest of this page is on the live site.