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이 따로 없기 때문에 멤버변수로 제어하는 방식으로 추가해 놓았다.
'Programming > Python' 카테고리의 다른 글
| python - decorator (0) | 2014.03.25 |
|---|---|
| python - 인코딩 관련 (0) | 2014.03.02 |
| python - dumpcode (0) | 2014.02.26 |
| python - ROL, ROR (2) | 2013.12.14 |
| RC4 알고리즘 - python (1) | 2013.12.14 |