2. threading
두 번째로 threading 모듈은 thread 클래스를 상속받아 사용하는 모듈입니다.
클래스가 threading.Thread를 상속받아 사용하게 됩니다.
java와 마찬가지로 run 메소드를 오버라이드 하여 각 각 선언된 클래스를 통해
Class_name.start()를 작동시키면 run 메소드가 작동하게 됩니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
class myThread (threading.Thread): | |
def __init__(self, name, delay): | |
threading.Thread.__init__(self) | |
self.name = name | |
self.delay = delay | |
def run(self): | |
print "Starting " + self.name | |
print_count(self.name, self.delay, 5) | |
print "Exiting " + self.name | |
def print_count(threadName, delay, counter): | |
while counter: | |
time.sleep(delay) | |
print "%s: %d" % (threadName, counter) | |
counter -= 1 | |
thread1 = myThread("Thread_1", 1) | |
thread2 = myThread("Thread_2", 2) | |
thread1.start() | |
thread2.start() | |
print "Exiting Main Thread" |
class myThread (threading.thread):를 통해 클래스를 선언 한 뒤
생성자를 통해 thread의 name과 delay time을 인자로 받습니다.
이 후 thread1.start()를 통해 run 메소드를 작동시킵니다.
run 메소듣 내부에서는 print_count함수를 호출하여 5회 각 각 1초와 2초의 딜레이를 부여해 내용을 출력합니다.
아래는 출력 내용입니다.
Starting Thread_1
Exiting Main Thread
Starting Thread_2
Thread_1: 5
Thread_2: 5Thread_1: 4
Thread_1: 3
Thread_2: 4
Thread_1: 2
Thread_1: 1
Exiting Thread_1
Thread_2: 3
Thread_2: 2
Thread_2: 1
Exiting Thread_2