Programming/Python

python - Thread 사용

bbolmin 2014. 3. 1. 09:43


Threading 모듈




(1). 아래와 같이 threading 모듈로 thread동작 함수를 등록해서 간단하게 사용할 수 있다.




import threading

def example(argv_0):
    print argv_0


th = threading.Thread(target=example, args=('hi',))
th.start()
th.join()





(2). Thread객체를 상속해서 run메소드를 재정의 한다.




import time, threading


class MyExample(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__suspend = False
        self.__exit = False

    def run(self):
        while True:
            ### Suspend ###
            while self.__suspend:
                time.sleep(0.5)
                
            ### Process ###
            print 'Thread process !!!'

            ### Exit ###
            if self.__exit:
                break
            
    def mySuspend(self):
        self.__suspend = True
        
    def myResume(self):
        self.__suspend = False
        
    def myExit(self):
        self.__exit = True


lock = threading.Lock()

th = MyExample()
th.start()
time.sleep(1)

### suspend 
th.mySuspend()
with lock:
    print 'Suspend Thread ....'
time.sleep(1)

### resume
th.myResume()
with lock:
    print 'Resume Thread ....'
time.sleep(1)

### exit
th.myExit()



- python Thread에 Suspend, Resume, Exit이 따로 없기 때문에 멤버변수로 제어하는 방식으로 추가해 놓았다.