Python 스레드 일시 중지, 재개, 종료
Python의 스레딩 모듈이 멀티 스레딩을 구현할 수 있다는 것은 모두 알고 있지만 모듈은 일시 중지를 제공하지 않습니다. , 재개 및 스레드를 중지하려면 스레드 개체가 시작 메서드를 호출하면 해당 메서드 함수가 완료될 때까지만 기다릴 수 있습니다. 즉, 일단 시작된 스레드는 제어할 수 없습니다. 일반적인 방법은 루프 플래그 비트를 결정하고 플래그 비트가 미리 정해진 값에 도달하면 루프를 종료하는 것입니다. 이렇게 하면 스레드를 종료할 수 있지만 스레드를 일시 중지하고 다시 시작하는 것이 약간 어렵습니다. 스레딩에서 Event 개체의 wait 메서드에 대한 설명을 보면
wait([timeout]) Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. 阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为True, 或者到达了可选的timeout时间. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. 当给定了timeout参数且不为None, 它应该是一个浮点数,以秒为单位指定操作的超时(或是分数)。 此方法在退出时返回内部标志,因此除非给定了超时且操作超时,否则它将始终返回True。 Changed in version 2.7: Previously, the method always returned None. 2.7版本以前, 这个方法总会返回None.
wait라는 차단 메커니즘을 사용하는 경우 일시 중지 및 복구를 달성한 다음 루프 판단 플래그 비트에 협력하면 종료할 수 있습니다.
#!/usr/bin/env python # coding: utf-8 import threading import time class Job(threading.Thread): def __init__(self, *args, **kwargs): super(Job, self).__init__(*args, **kwargs) self.__flag = threading.Event() # 用于暂停线程的标识 self.__flag.set() # 设置为True self.__running = threading.Event() # 用于停止线程的标识 self.__running.set() # 将running设置为True def run(self): while self.__running.isSet(): self.__flag.wait() # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回 print time.time() time.sleep(1) def pause(self): self.__flag.clear() # 设置为False, 让线程阻塞 def resume(self): self.__flag.set() # 设置为True, 让线程停止阻塞 def stop(self): self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话 self.__running.clear() # 设置为False
다음은 테스트입니다. 코드:
a = Job() a.start() time.sleep(3) a.pause() time.sleep(3) a.resume() time.sleep(3) a.pause() time.sleep(2) a.stop()
테스트 결과:
이로써 일시 중지, 재개 기능이 완료됩니다. 하지만 여기에는 일시 중지 여부가 즉각적이지 않고 실행 함수 내부의 작업이 플래그 비트 판단에 도달할 때까지 기다려야 한다는 단점이 있습니다.
하지만 이것이 반드시 나쁜 것은 아닙니다. 실행 함수에 파일 작업이나 데이터베이스 작업 등이 포함되어 완전히 실행한 후 종료하면 대신 나머지 리소스 해제 작업에 대한 코드를 실행할 수 있습니다(예: 각종 종료) 프로그램의 파일 연산자가 상한을 초과하거나 데이터베이스 연결이 해제되지 않는 상황 등 당황스러운 일은 없을 것입니다.
위 내용은 Python 스레드의 일시 중지, 재개 및 종료에 대한 자세한 설명과 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

다음 단계를 통해 Numpy를 사용하여 다차원 배열을 만들 수 있습니다. 1) Numpy.array () 함수를 사용하여 NP.Array ([[1,2,3], [4,5,6]]과 같은 배열을 생성하여 2D 배열을 만듭니다. 2) np.zeros (), np.ones (), np.random.random () 및 기타 함수를 사용하여 특정 값으로 채워진 배열을 만듭니다. 3) 서브 어레이의 길이가 일관되고 오류를 피하기 위해 배열의 모양과 크기 특성을 이해하십시오. 4) NP.Reshape () 함수를 사용하여 배열의 모양을 변경하십시오. 5) 코드가 명확하고 효율적인지 확인하기 위해 메모리 사용에주의를 기울이십시오.

BroadcastingInnumpyIsamethodtoperformoperationsonArraysoffferentShapesByAutomicallyAligningThem.itsimplifiesCode, enourseadability, andboostsperformance.here'showitworks : 1) smalraysarepaddedwithonestomatchdimenseare

forpythondatastorage, chooselistsforflexibilitywithmixeddatatypes, array.arrayformemory-effic homogeneousnumericaldata, andnumpyarraysforadvancednumericalcomputing.listsareversatilebutlessefficipforlargenumericaldatasets.arrayoffersamiddlegro

pythonlistsarebetterthanarraysformanagingDiversEdatatypes.1) 1) listscanholdementsofdifferentTypes, 2) thearedynamic, weantEasyAdditionSandremovals, 3) wefferintufiveOperationsLikEslicing, but 4) butiendess-effectorlowerggatesets.

toaccesselementsInapyThonArray : my_array [2] AccessHetHirdElement, returning3.pythonuseszero 기반 인덱싱 .1) 사용 positiveAndnegativeIndexing : my_list [0] forthefirstelement, my_list [-1] forstelast.2) audeeliciforarange : my_list

기사는 구문 모호성으로 인해 파이썬에서 튜플 이해의 불가능성에 대해 논의합니다. 튜플을 효율적으로 생성하기 위해 튜플 ()을 사용하는 것과 같은 대안이 제안됩니다. (159 자)

이 기사는 파이썬의 모듈과 패키지, 차이점 및 사용법을 설명합니다. 모듈은 단일 파일이고 패키지는 __init__.py 파일이있는 디렉토리이며 관련 모듈을 계층 적으로 구성합니다.

기사는 Python의 Docstrings, 사용법 및 혜택에 대해 설명합니다. 주요 이슈 : 코드 문서 및 접근성에 대한 문서의 중요성.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

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