파이썬(Python)/문법

[Python] 멀티스레드란? 사용법, 예제 (Multi thread, target, args, start, join)

끄적끄적아무거나 2022. 6. 30. 09:01
반응형

 

목차

     

     

     

     

    앞서 멀티 프로세스(Multi process)의 의미와 사용 방법에 대해 이야기 해보았습니다(https://scribblinganything.tistory.com/566). 이번 시간에는 멀티 쓰레드(Multithreading)에 대해 알아 보겠습니다.

     

     

    파이썬 멀티스레드(Multi threading)란?

    멀티프로세스는 각 각의 프로세스가 독립된 메모리를 가지고 동작한다고 하였습니다. 그러므로 컴퓨터 내의 자원을 많이 소모하게 됩니다.

     

    하지만 드레드(Thread)의 경우 Thread라는 의미가 가지는 실과 같이 하나의 프로세스 내에서 여러개의 실들이 각 각 움직이게 됩니다. 그리고 그 실(Thread)은 내부의 메모리를 공유하면서 각 각 움직이므로 프로그램이 가벼워 집니다. 

     

    Thread의 특징을 정리하면 아래와 같습니다.

    • 메모리 공유
    • 독립된 register 사용
    • 독립된 stack 사용

     

    아래의 예제들과 함께 쉽게 이해해보도록 하겠습니다. 

     

     

     

     

     

    파이썬 멀티스레드(Multi thread) 선언

    Thread 선언은 threading의 Thread로 합니다. 그리고 Tread의 시작은 start으로 종료는 join으로 합니다.

     

    target은 thread에서 동작시킬 함수 값을 결정하고 args는 입력값을 의미 합니다.

     

    아래 예제는 기본 thread 예제로 2개의 thread를 시행하고 각 각에 다른 time.sleep을 줘서 독립적으로 움직이는지를 확인합니다.

     

    예제 코드>>

    import threading
    import time
      
    def func0(list_var):
        for x in list_var:
            print(x)
            time.sleep(0.5)  
      
    def func1(list_var):
        for x in list_var:
            print(x)
            time.sleep(1)  
      
    if __name__ == "__main__":
        t1 = threading.Thread(target=func0, args=([1,2,3],))
        t2 = threading.Thread(target=func1, args=(["a","b","c"],))
      
        t1.start()
        t2.start()
      
        t1.join()
        t2.join()

    4~12번 라인: func0, func1 함수 정의

    7번 라인: 리스트 값을 하나씩 출력하면서 0.5초 delay를 줍니다.

    15~16번 라인: thread 선언

    18~19번 라인: thread 시작

    21~22번 라인: thread 종료

     

     

    결과>>

    1
    a
    2
    3b
    
    c

    스레드가 각 각 독립적으로 출력 했음을 알 수 있습니다. 

     

     

     

     

     

     

    파이썬 멀티스레드(Multi thread) 이름, 프로세스 명 확인

     

    current_thread.name 함수를 사용해서 현재 thread의 이름과 os.getpid 함수로 현재 process 명을 확인하겠습니다.

     

    멀티 프로세스와 다르게 멀티스레드는 동일한 프로세스를 사용하므로 결과는 다른 thread 이름을 가지면서 동일한 process 명을 가질 것으로 생각 됩니다.

     

    • threading.current_thread(): 현재 스레드 값 확인
    • os.getpid(): 현재 프로세스값 확인

     

    예제 코드>>

    import threading
    import os
      
    def func0():
        print("func0 Thread Name : ", threading.current_thread().name)
        print("func0 Process ID : ", os.getpid())
      
    def func1():
        print("func1 Thread Name : ", threading.current_thread().name)
        print("func1 Process ID : ", os.getpid())
      
    if __name__ == "__main__":
      
        print("Main Thread Name : ", threading.current_thread().name)
        print("Main Process ID : ", os.getpid())  
    
        t0 = threading.Thread(target=func0, name='t0')
        t1 = threading.Thread(target=func1, name='t1')  
      
        t0.start()
        t1.start()
      
        t0.join()
        t1.join()

     

    결과>>

    Main Thread Name :  MainThread
    Main Process ID :  16060
    func0 Thread Name : t0
    func0 Process ID :  16060
    func1 Thread Name : t1
    func1 Process ID :  16060

    결과에서 보듯이 process ID는 동일하고 thread는 각 각 다른 이름을 가집니다. thread로 동시 진행되기 때문에 위와 같은 결과가 아닌 순서가 뒤집힐 수 있습니다.

     

     

    다음 장에서는 thread 간에 데이터를 공유하고 주고 받는 방법에 대해 알아보겠습니다.

    반응형