찾다
백엔드 개발파이썬 튜토리얼Python의 동시 미래 모듈 소개(코드)

이 기사는 Python의 동시 미래 모듈에 대한 소개(코드)를 제공합니다. 이는 특정 참조 가치가 있으므로 도움이 될 수 있습니다.

concurrent.futures 모듈

이 모듈의 주요 기능은 ThreadPoolExecutor 및 ProcessPoolExecutor 클래스입니다. 두 클래스는 모두 Concurrent.futures._base.Executor 클래스에서 상속되며 서로 다른 스레드 또는 프로세스에서 실행되고 호출 가능합니다. 개체는 모두 내부적으로 작업자 스레드 또는 프로세스 풀을 유지 관리합니다.

ThreadPoolExecutor 및 ProcessPoolExecutor 클래스는 고급 클래스입니다. 대부분의 경우 구현 세부 사항에 신경 쓰지 않고 사용 방법만 배우면 됩니다.

####ProcessPoolExecutor 클래스

>class ThreadPoolExecutor(concurrent.futures._base.Executor)

>|  This is an abstract base class for concrete asynchronous executors.

>|  Method resolution order:

>|      ThreadPoolExecutor

 |      concurrent.futures._base.Executor

 |      builtins.object

 |

 |  Methods defined here:

 |

 |  init(self, max_workers=None, thread_name_prefix='')

 |      Initializes a new ThreadPoolExecutor instance.

 |

 |      Args:

 |          max_workers: The maximum number of threads that can be used to

 |              execute the given calls.

 |          thread_name_prefix: An optional name prefix to give our threads.

 |

 |  shutdown(self, wait=True)

 |      Clean-up the resources associated with the Executor.

 |

 |      It is safe to call this method several times. Otherwise, no other

 |      methods can be called after this one.

 |

 |      Args:

 |          wait: If True then shutdown will not return until all running

 |              futures have finished executing and the resources used by the

 |              executor have been reclaimed.

 |

 |  submit(self, fn, *args, **kwargs)

 |      Submits a callable to be executed with the given arguments.

 |

 |      Schedules the callable to be executed as fn(*args, **kwargs) and returns

 |      a Future instance representing the execution of the callable.

 |

 |      Returns:

 |          A Future representing the given call.

 |

 |  ----------------------------------------------------------------------

 |  Methods inherited from concurrent.futures._base.Executor:

 |

 |  enter(self)

 |

 |  exit(self, exc_type, exc_val, exc_tb)

 |

 |  map(self, fn, *iterables, timeout=None, chunksize=1)

 |      Returns an iterator equivalent to map(fn, iter).

 |

 |      Args:

 |          fn: A callable that will take as many arguments as there are

 |              passed iterables.

 |          timeout: The maximum number of seconds to wait. If None, then there

 |              is no limit on the wait time.

 |          chunksize: The size of the chunks the iterable will be broken into

 |              before being passed to a child process. This argument is only

 |              used by ProcessPoolExecutor; it is ignored by

 |              ThreadPoolExecutor.

 |

 |      Returns:

 |          An iterator equivalent to: map(func, *iterables) but the calls may

 |          be evaluated out-of-order.

 |

 |      Raises:

 |          TimeoutError: If the entire result iterator could not be generated

 |              before the given timeout.

 |          Exception: If fn(*args) raises for any values.

초기화에서는 max_workers 매개변수의 값으로 최대 프로세스 수를 지정할 수 있습니다. 이 값은 일반적으로 현재 실행 중인 시스템의 코어 수로 지정될 필요가 없습니다. os.cpu_count()로 얻을 수 있습니다. 클래스 포함된 메소드:

  1. map() 메소드는 Python의 내장 메소드 map()과 유사합니다. 즉, 매개변수는 다음과 같습니다.

  • 호출 가능한 함수 fn

  • 반복자는 iterables

  • timeout timeout

  • chuncksize 1보다 크면 반복자는 덩어리로 처리됩니다

---->> 함수에는 특징이 있습니다. 결과를 반환하는 순서와 호출 시작이 일관됩니다. 호출 프로세스 중에 차단이 없습니다. 즉, 전자가 호출되기 전에 후자의 실행이 종료될 수 있습니다.

처리하기 전에 모든 결과를 얻어야 하는 경우 futures.as_completed 함수와 함께 submit() 메서드를 사용하도록 선택할 수 있습니다.

  1. shutdown() 메소드, 현재 실행기(executor)와 관련된 모든 리소스 정리

  2. submit() 메소드, 사용을 위해 호출 가능한 객체를 fn에 제출

  3. Concurrent.futures._base.Executor에서 상속된 __enter__() 및 __exit__() 메서드. 이는 ProcessPoolExecutor 객체가 with 문에서 사용될 수 있음을 의미합니다.

from concurrent import futures
with futures.ProcessPoolExecutor(max_works=3) as executor:
     executor.map()

ThreadPoolExecutor 클래스

class ThreadPoolExecutor(concurrent.futures._base.Executor)

 |  This is an abstract base class for concrete asynchronous executors.

 |

 |  Method resolution order:

 |      ThreadPoolExecutor

 |      concurrent.futures._base.Executor

 |      builtins.object

 |

 |  Methods defined here:

 |

 |  init(self, max_workers=None, thread_name_prefix='')

 |      Initializes a new ThreadPoolExecutor instance.

 |

 |      Args:

 |          max_workers: The maximum number of threads that can be used to

 |              execute the given calls.

 |          thread_name_prefix: An optional name prefix to give our threads.

 |

 |  shutdown(self, wait=True)

 |      Clean-up the resources associated with the Executor.

 |

 |      It is safe to call this method several times. Otherwise, no other

 |      methods can be called after this one.

 |

 |      Args:

 |          wait: If True then shutdown will not return until all running

 |              futures have finished executing and the resources used by the

 |              executor have been reclaimed.

 |

 |  submit(self, fn, *args, **kwargs)

 |      Submits a callable to be executed with the given arguments.

 |

 |      Schedules the callable to be executed as fn(*args, **kwargs) and returns

 |      a Future instance representing the execution of the callable.

 |

 |      Returns:

 |          A Future representing the given call.

 |

 |  ----------------------------------------------------------------------

 |  Methods inherited from concurrent.futures._base.Executor:

 |

 |  enter(self)

 |

 |  exit(self, exc_type, exc_val, exc_tb)

 |

 |  map(self, fn, *iterables, timeout=None, chunksize=1)

 |      Returns an iterator equivalent to map(fn, iter).

 |

 |      Args:

 |          fn: A callable that will take as many arguments as there are

 |              passed iterables.

 |          timeout: The maximum number of seconds to wait. If None, then there

 |              is no limit on the wait time.

 |          chunksize: The size of the chunks the iterable will be broken into

 |              before being passed to a child process. This argument is only

 |              used by ProcessPoolExecutor; it is ignored by

 |              ThreadPoolExecutor.

 |

 |      Returns:

 |          An iterator equivalent to: map(func, *iterables) but the calls may

 |          be evaluated out-of-order.

 |

 |      Raises:

 |          TimeoutError: If the entire result iterator could not be generated

 |              before the given timeout.

 |          Exception: If fn(*args) raises for any values.

는 하나는 처리 프로세스이고 다른 하나는 실제 필요에 따라 선택할 수 있는 처리 스레드라는 점을 제외하면 ProcessPoolExecutor 클래스와 매우 유사합니다.

Example

from time import sleep, strftime
from concurrent import futures


def display(*args):
    print(strftime('[%H:%M:%S]'), end="")
    print(*args)


def loiter(n):
    msg = '{}loiter({}): doing nothing for {}s'
    display(msg.format('\t'*n, n, n))
    sleep(n)
    msg = '{}loiter({}): done.'
    display(msg.format('\t'*n, n))
    return n*10


def main():
    display('Script starting')
    executor = futures.ThreadPoolExecutor(max_workers=3)
    results = executor.map(loiter, range(5))
    display('results:', results)
    display('Waiting for inpidual results:')
    for i, result in enumerate(results):
        display('result {} : {}'.format(i, result))


if __name__ == '__main__':
    main()

실행 결과:

[20:32:12]Script starting
[20:32:12]loiter(0): doing nothing for 0s
[20:32:12]loiter(0): done.
[20:32:12]      loiter(1): doing nothing for 1s
[20:32:12]              loiter(2): doing nothing for 2s
[20:32:12]results: <generator>.result_iterator at 0x00000246DB21BC50>
[20:32:12]Waiting for inpidual results:
[20:32:12]                      loiter(3): doing nothing for 3s
[20:32:12]result 0 : 0
[20:32:13]      loiter(1): done.
[20:32:13]                              loiter(4): doing nothing for 4s
[20:32:13]result 1 : 10
[20:32:14]              loiter(2): done.
[20:32:14]result 2 : 20
[20:32:15]                      loiter(3): done.
[20:32:15]result 3 : 30
[20:32:17]                              loiter(4): done.
[20:32:17]result 4 : 40</generator>

실행 결과는 컴퓨터마다 다를 수 있습니다.

예제에서는 max_workers=3으로 설정되어 있으므로 코드가 실행되기 시작하자마자 3개 객체(0, 1, 2)가 loiter() 연산으로 실행되고 3초 후에 객체 0의 연산이 종료됩니다. 결과 0을 얻은 후 개체 3이 막 실행되기 시작했습니다. 마찬가지로 개체 4의 실행 시간은 개체 1의 실행 결과인 결과 1이 인쇄된 이후입니다.

관련 권장 사항:

Python이 future를 통해 동시성 문제를 처리하는 방법에 대한 자세한 예

위 내용은 Python의 동시 미래 모듈 소개(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?Apr 26, 2025 am 12:13 AM

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?Apr 26, 2025 am 12:05 AM

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.

파이썬 목록에서 요소에 어떻게 액세스합니까?파이썬 목록에서 요소에 어떻게 액세스합니까?Apr 26, 2025 am 12:03 AM

ToaccesselementsInapyThonlist, 사용 인덱싱, 부정적인 인덱싱, 슬라이스, 오리 화.

어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구