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()로 얻을 수 있습니다. 클래스 포함된 메소드:
map() 메소드는 Python의 내장 메소드 map()과 유사합니다. 즉, 매개변수는 다음과 같습니다.
-
호출 가능한 함수 fn
-
반복자는 iterables
timeout timeout
chuncksize 1보다 크면 반복자는 덩어리로 처리됩니다
---->> 함수에는 특징이 있습니다. 결과를 반환하는 순서와 호출 시작이 일관됩니다. 호출 프로세스 중에 차단이 없습니다. 즉, 전자가 호출되기 전에 후자의 실행이 종료될 수 있습니다.
처리하기 전에 모든 결과를 얻어야 하는 경우 futures.as_completed 함수와 함께 submit() 메서드를 사용하도록 선택할 수 있습니다.
shutdown() 메소드, 현재 실행기(executor)와 관련된 모든 리소스 정리
submit() 메소드, 사용을 위해 호출 가능한 객체를 fn에 제출
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 object Executor.map.<locals>.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
실행 결과는 컴퓨터마다 다를 수 있습니다.
예제에서는 max_workers=3으로 설정되어 있으므로 코드가 실행되기 시작하자마자 3개 객체(0, 1, 2)가 loiter() 연산으로 실행되고 3초 후에 객체 0의 연산이 종료됩니다. 결과 0을 얻은 후 개체 3이 막 실행되기 시작했습니다. 마찬가지로 개체 4의 실행 시간은 개체 1의 실행 결과인 결과 1이 인쇄된 이후입니다.
관련 권장 사항:
Python이 future를 통해 동시성 문제를 처리하는 방법에 대한 자세한 예
위 내용은 Python의 동시 미래 모듈 소개(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

VS 코드는 파이썬을 작성하는 데 사용될 수 있으며 파이썬 애플리케이션을 개발하기에 이상적인 도구가되는 많은 기능을 제공합니다. 사용자는 다음을 수행 할 수 있습니다. Python 확장 기능을 설치하여 코드 완료, 구문 강조 및 디버깅과 같은 기능을 얻습니다. 디버거를 사용하여 코드를 단계별로 추적하고 오류를 찾아 수정하십시오. 버전 제어를 위해 git을 통합합니다. 코드 서식 도구를 사용하여 코드 일관성을 유지하십시오. 라인 도구를 사용하여 잠재적 인 문제를 미리 발견하십시오.

VS 코드 확장은 악의적 인 코드 숨기기, 취약성 악용 및 합법적 인 확장으로 자위하는 등 악성 위험을 초래합니다. 악의적 인 확장을 식별하는 방법에는 게시자 확인, 주석 읽기, 코드 확인 및주의해서 설치가 포함됩니다. 보안 조치에는 보안 인식, 좋은 습관, 정기적 인 업데이트 및 바이러스 백신 소프트웨어도 포함됩니다.

VS 코드는 Windows 8에서 실행될 수 있지만 경험은 크지 않을 수 있습니다. 먼저 시스템이 최신 패치로 업데이트되었는지 확인한 다음 시스템 아키텍처와 일치하는 VS 코드 설치 패키지를 다운로드하여 프롬프트대로 설치하십시오. 설치 후 일부 확장은 Windows 8과 호환되지 않을 수 있으며 대체 확장을 찾거나 가상 시스템에서 새로운 Windows 시스템을 사용해야합니다. 필요한 연장을 설치하여 제대로 작동하는지 확인하십시오. Windows 8에서는 VS 코드가 가능하지만 더 나은 개발 경험과 보안을 위해 새로운 Windows 시스템으로 업그레이드하는 것이 좋습니다.

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

vs 코드에서는 다음 단계를 통해 터미널에서 프로그램을 실행할 수 있습니다. 코드를 준비하고 통합 터미널을 열어 코드 디렉토리가 터미널 작업 디렉토리와 일치하는지 확인하십시오. 프로그래밍 언어 (예 : Python의 Python Your_file_name.py)에 따라 실행 명령을 선택하여 성공적으로 실행되는지 여부를 확인하고 오류를 해결하십시오. 디버거를 사용하여 디버깅 효율을 향상시킵니다.
