python thread example

 python에서 thread를 생성하고자 할 때는 'threading' 모듈의 Thread class를 사용하면 된다.

import threading


Thread objects

 Thread class를 사용하여 thread를 생성하는 방법에는 2 가지가 있다. 

  • Thread class 생성시 thread로 사용할 함수를 전달해 thread를 생성
  • Thread class의 run() 메소드를 오버라이드해 thread를 생성


1. 함수 사용 thread 생성 예

c/c++등에서 사용되는 방법과 유사하게 thread 함수를 전달해 thread를 생성하는 방법이다.

class threading.Thread( group = None , target = None , name = None , args = () , kwargs = {} , * , daemon = None )

thread 생성시 target 파라미터에 thread 함수를 전달하면 된다. 기본값은 None이며, None인 경우 아무것도 호출되지 않음을 의미한다. args에 thread 함수의 인수를 전달하며, 튜플 형식이다.

아래는 함수를 전달하여 thread를 사용하는 예제 코드이다.

import threading
import time

def workingTh(param1,param2):
    print('workingTh is started!!')
    time.sleep(5)
    print('workingTh result:',param1 + param2)
    print('workingTh is ended!!')
    
def main():
    th = threading.Thread(target=workingTh,name='working thread',args=(10,10),daemon=True)
    
    try:
        th.start()
    except RuntimeError:
        print('RuntimeError: start ',th.getName())
            
    if th.is_alive():
        try:
            th.join(timeout=100)
        except RuntimeError:
            print('RuntimeError: join ',th.getName())
    
    print('main is ended')


실행 결과

workingTh is started!!
workingTh result: 20
workingTh is ended!!
main thread is ended


Thread를 생성한 후 start()를 호출해야 thread가 실행된다. 만약 실행될 thread 객체가 없다면 RunTimeError가 발생하다.

Thread 종료를 기다리는 join()은 is_alive()를 사용해 thread가 동작중인경우 사용해야 한다. Thread가 종료된 상태에 Join()을 호출하면 RuntimeError가 발생한다. Join의 timeout인자의 단위는 초(second)이며, timeout=None인 경우 Thread가 종료될 때 까지 기다린다.

daemon 파라미터는 Thread를 daemon Thread로 만들지 여부를 결정한다. daemon인 경우 main thread가 종료될 때 생성된 thread도 같이 종료된다.

[Note] Python에서는 thread 함수의 리턴 값을 받지 않는다. 만약 계산 결과를 얻고자 할 경우 함수의 파라메터를 class같은 오브젝트로 만들어 전달해 계산 결과를 저장해 사용할 수도 있다.

class my_param(object):
    x = 0
    y = 0
    result = 0

def workingTh2(param):
    param.result = param.x + param.y

def main():
    param = my_param()
    param.x = 10
    param.y = 10
    th = threading.Thread(target=workingTh2,name='working thread',args=(param,),daemon=True)
    
    try:
        th.start()
    except RuntimeError:
        print('RuntimeError: start ',th.getName())
            
    if th.is_alive():
        try:
            th.join(timeout=100)
        except RuntimeError:
            print('RuntimeError: join',th.getName())
    
    print('main thread is ended. result:',param.result)


2. run() 메소드 오버라이딩 thread 생성 예

threading.Thead class의 멤버인 run()함수는 Thread시작시 호출된다. 이 run()함수를 오버라이딩하여 Thread를 생성할 수 있다. 

import threading
import time

class workingTh3(threading.Thread):
    x = 0
    y = 0
    result = 0
    
    def run(self):
        for _ in range(5):
            print('run')
            self.result = self.x+self.y
            time.sleep(1)
            
def main3():
    th = workingTh3()
    th.x = 10
    th.y = 10
        
    try:
        th.start()
    except RuntimeError:
        print('RuntimeError: start ',th.getName())
            
    if th.is_alive():
        try:
            th.join(timeout=100)
        except RuntimeError:
            print('RuntimeError: join',th.getName())
    
    print('main3 thread is ended. result:',th.result)


실행 결과

run
run
run
run
run
main3 thread is ended. result: 20


관련 포스트

python thread lock example
python event example

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

mkfs.fat Device or resource busy 에러 해결법

python winsound를 이용한 윈도우 환경에서 소리 재생 예제

Embedded Linux USB Ethernet Gadget 사용하기