> 백엔드 개발 > 파이썬 튜토리얼 > 파이썬에서 스레드를 닫는 방법

파이썬에서 스레드를 닫는 방법

coldplay.xixi
풀어 주다: 2023-01-03 09:26:59
원래의
19448명이 탐색했습니다.

Python에서 스레드를 닫는 방법: 먼저 스레딩을 가져오고 메서드를 정의한 다음 스레드를 정의하고, 대상은 실행할 메서드를 가리키며, 마지막으로 스레드를 중지합니다. 코드는 [stop_thread(myThread)]입니다.

파이썬에서 스레드를 닫는 방법

이 튜토리얼의 운영 환경: Windows 7 시스템, Python 버전 3.9, DELL G3 컴퓨터.

Python에서 스레드를 닫는 방법:

1. 스레드 시작

먼저 스레드 가져오기

import threading
로그인 후 복사

그런 다음 메서드를 정의합니다

    def serial_read():
   ...
   ...
로그인 후 복사

그런 다음 스레드를 정의하고, 대상은 실행할 메서드를 가리킵니다

myThread = threading.Thread(target=serial_read)
로그인 후 복사

시작하세요

myThread.start()
로그인 후 복사

둘째, 스레드를 중지하세요

더 이상은 아니고 바로 코드로 가겠습니다

import inspect
import ctypes
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)
로그인 후 복사

스레드 중지

stop_thread(myThread)
로그인 후 복사

관련 무료 학습 권장사항: python 비디오 튜토리얼

위 내용은 파이썬에서 스레드를 닫는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿