본문 바로가기

Python/Advanced

[Python] Thread(1) - Basic

import logging
import threading
import time

# 스레드 실행 함수
def thread_func(name):
    logging.info("**Sub-Thread %s: starting", name)
    time.sleep(3)
    logging.info("**Sub-Thread %s: finishing", name)

# 메인 영역
if __name__ == "__main__":
    # Logging format 설정
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
    logging.info("Main-Thread : before creating thread")
    
    # 함수 인자 확인
    x = threading.Thread(target=thread_func, args=('First',))
    
    logging.info("Main-Thread : before running thread")
   
    # 서브 스레드 시작
    x.start()
   
    logging.info("Main-Thread : wait for the thread to finish")
    
    # 주석 전후 결과 확인, 자식 스레드가 끝날때까지 메인 스레드 기다린 후 종료됨.자식스레드기다림
    x.join() # 메인스레드가 기다림.
    
    logging.info("Main-Thread : all done")
------------------------------------------------[result]
# 메인스레드가 기다리는 버전.
21:53:50: Main-Thread : before creating thread
21:53:50: Main-Thread : before running thread
21:53:50: **Sub-Thread First: starting
21:53:50: Main-Thread : wait for the thread to finish
21:53:53: **Sub-Thread First: finishing
21:53:53: Main-Thread : all done

# x.join() 주석처리한 경우, 메인스레드 바로 종료
21:54:11: Main-Thread : before creating thread
21:54:11: Main-Thread : before running thread
21:54:11: **Sub-Thread First: starting
21:54:11: Main-Thread : wait for the thread to finish
21:54:11: Main-Thread : all done
21:54:14: **Sub-Thread First: finishing