예제가 포함된 Python 스레딩 모듈에 대한 빠른 가이드

王林
풀어 주다: 2024-09-12 14:17:31
원래의
518명이 탐색했습니다.

A Quick Guide to the Python threading Module with Examples

소개

Python의 스레딩 모듈은 스레드를 생성하고 관리할 수 있는 고급 인터페이스를 제공하여 코드를 동시에 실행할 수 있습니다. 이는 I/O 바인딩 작업과 같이 병렬로 실행될 수 있는 작업에 특히 유용할 수 있습니다. 다음은 스레딩 모듈에서 일반적으로 사용되는 메서드 및 함수 목록과 간단한 예입니다.

1. 쓰레드()

Thread 클래스는 스레딩 모듈의 핵심입니다. 이 클래스를 사용하여 새 스레드를 만들고 시작할 수 있습니다.

import threading

def print_numbers():
    for i in range(5):
        print(i)

t = threading.Thread(target=print_numbers)
t.start()  # Starts a new thread
t.join()   # Waits for the thread to finish
로그인 후 복사

2. 시작()

스레드 활동을 시작합니다.

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
로그인 후 복사

3. 가입([시간 초과])

join() 메서드가 호출된 스레드가 종료될 때까지 호출 스레드를 차단합니다. 선택적으로 시간 초과를 지정할 수 있습니다.

t = threading.Thread(target=print_numbers)
t.start()
t.join(2)  # Waits up to 2 seconds for the thread to finish
로그인 후 복사

4. is_alive()

스레드가 아직 실행 중이면 True를 반환합니다.

t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive())  # True if the thread is still running
로그인 후 복사

5. 현재_스레드()

호출 스레드를 나타내는 현재 Thread 객체를 반환합니다.

import threading

def print_current_thread():
    print(threading.current_thread())

t = threading.Thread(target=print_current_thread)
t.start()  # Prints the current thread info
로그인 후 복사

6. 열거()

현재 살아있는 모든 Thread 객체의 목록을 반환합니다.

t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()

print(threading.enumerate())  # Lists all active threads
로그인 후 복사

7. 활성_카운트()

현재 살아있는 Thread 객체의 수를 반환합니다.

print(threading.active_count())  # Returns the number of active threads
로그인 후 복사

8. 잠금()

Lock 객체는 경쟁 조건을 방지하는 데 사용되는 기본 잠금입니다. 이를 사용하면 한 번에 하나의 스레드만 공유 리소스에 액세스하도록 할 수 있습니다.

lock = threading.Lock()

def thread_safe_function():
    with lock:  # Acquires the lock
        # Critical section
        print("Thread-safe code")

t = threading.Thread(target=thread_safe_function)
t.start()
로그인 후 복사

9. 알락()

재진입 잠금을 사용하면 스레드가 자신을 차단하지 않고 여러 번 잠금을 획득()할 수 있습니다.

lock = threading.RLock()

def reentrant_function():
    with lock:
        with lock:  # Same thread can acquire the lock again
            print("Reentrant lock example")

t = threading.Thread(target=reentrant_function)
t.start()
로그인 후 복사

10. 조건()

조건 개체를 사용하면 스레드가 특정 조건이 충족될 때까지 기다릴 수 있습니다.

condition = threading.Condition()

def thread_wait():
    with condition:
        condition.wait()  # Wait for the condition
        print("Condition met")

def thread_notify():
    with condition:
        condition.notify()  # Notify the waiting thread

t1 = threading.Thread(target=thread_wait)
t2 = threading.Thread(target=thread_notify)
t1.start()
t2.start()
로그인 후 복사

11. 이벤트()

이벤트 개체는 스레드 간 신호를 보내는 데 사용됩니다. 스레드는 이벤트가 설정될 때까지 기다릴 수 있고 다른 스레드는 이벤트를 설정할 수 있습니다.

event = threading.Event()

def wait_for_event():
    event.wait()  # Wait until the event is set
    print("Event has been set")

t = threading.Thread(target=wait_for_event)
t.start()
event.set()  # Set the event to allow the thread to continue
로그인 후 복사

12. 세마포어()

세마포어 개체를 사용하면 리소스에 동시에 액세스할 수 있는 스레드 수를 제한할 수 있습니다.

semaphore = threading.Semaphore(2)  # Only 2 threads can access the resource at once

def access_resource():
    with semaphore:
        print("Resource accessed")

t1 = threading.Thread(target=access_resource)
t2 = threading.Thread(target=access_resource)
t3 = threading.Thread(target=access_resource)

t1.start()
t2.start()
t3.start()
로그인 후 복사

13. 타이머(간격, 기능)

타이머 스레드는 지정된 간격 후에 함수를 실행합니다.

def delayed_function():
    print("Executed after delay")

timer = threading.Timer(3, delayed_function)
timer.start()  # Executes `delayed_function` after 3 seconds
로그인 후 복사

14. setDaemon(참)

데몬 스레드는 백그라운드에서 실행되며 기본 프로그램이 종료되면 자동으로 종료됩니다. setDaemon(True)을 호출하거나 daemon=True를 Thread 생성자에 전달하여 스레드를 데몬으로 만들 수 있습니다.

t = threading.Thread(target=print_numbers, daemon=True)
t.start()  # Daemon thread will exit when the main program ends
로그인 후 복사

결론

스레딩 모듈은 Python에서 동시성을 처리하기 위한 강력한 도구입니다. 스레드를 생성하고 제어하는 ​​여러 클래스와 메서드를 제공하므로 코드를 병렬로 쉽게 실행할 수 있습니다. 기본 Thread 객체 사용부터 Lock 및 Semaphore를 사용한 동기화 관리에 이르기까지 이 모듈은 동시 Python 프로그램을 작성하는 데 필수적입니다.

위 내용은 예제가 포함된 Python 스레딩 모듈에 대한 빠른 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!