Python threading

Happy_JG·2024년 4월 4일

Python

목록 보기
12/12

Python Threading 모듈

Python은 threading 모듈을 통해 병렬 프로그래밍을 지원한다. 이 모듈은 여러 작업을 동시에 실행하고 병렬로 처리하는 데 용이하다. 또한 CPU 사용률을 향상시키고 작업의 처리 속도를 높일 수 있다.

스레드(Thread)란?

스레드는 프로세스 내에서 실행되는 작은 실행 단위이다. 한 프로세스는 여러 개의 스레드를 가질 수 있으며, 각각의 스레드는 독립적으로 실행될 수 있다. 이를 통해 여러 작업을 동시에 처리하거나 병렬로 실행할 수 있습니다.

import threading
import time

# 각 스레드에서 실행할 함수
def print_numbers():
    for i in range(5):
        print(f"Thread {threading.current_thread().name}: {i}")
        time.sleep(1)  # 1초간 대기

# 메인 스레드
if __name__ == "__main__":
    # 스레드 생성
    thread1 = threading.Thread(target=print_numbers, name="Thread-1")
    thread2 = threading.Thread(target=print_numbers, name="Thread-2")

    # 스레드 시작
    thread1.start()
    thread2.start()

    # 메인 스레드에서도 일을 할 수 있음
    for i in range(5):
        print(f"Main Thread: {i}")
        time.sleep(1)

    # 모든 스레드가 실행을 마칠 때까지 대기
    thread1.join()
    thread2.join()

    print("모든 스레드 실행이 완료되었습니다.")

메인 스레드

threading.Thread(target=print_numbers, name="Thread-1")

target으로 메서드명을 지정하여 설정한다. 만약 해당 스레드명을 쓸 필요가 없다고 가정하자.

import threading
import time

#각 스레드에서 실행할 함수
def print_numbers():
    for i in range(5):
        print("hoho")
        time.sleep(1)  # 1초간 대기

# 메인 스레드
if __name__ == "__main__":
    # 스레드 생성
    thread1 = threading.Thread(target=print_numbers)
    thread2 = threading.Thread(target=print_numbers)

    # 스레드 시작
    thread1.start()
    thread2.start()

    # 메인 스레드에서도 일을 할 수 있음
    for i in range(5):
        print(f"Main Thread: {i}")
        time.sleep(1)

    # 모든 스레드가 실행을 마칠 때까지 대기
    thread1.join()
    thread2.join()

    print("모든 스레드 실행이 완료되었습니다.")

    print("모든 스레드 실행이 완료되었습니다.")

threading을 통해 기능을 확장할 수 있다.

profile
hello!

0개의 댓글