Python 프로그래밍 > Python - Thread (쓰레드)
등록일 : 2018-07-02 17:44
조회수 : 94,170
쓰레드는 프로세스 내에서 독립된 실행 흐름을 가진 코드를 말합니다.
하나의 작업을 하면서 동시에 다른 작업도 할 수 있습니다.
보통은 한 프로세스당 한개의 쓰레드를 갖고 있지만, 상황에 따라서는 여러개의 쓰레드를 가질 수 있습니다.
이것을 멀티쓰레드(Mul-Thread) 라고 합니다.
import threading
from time import sleep
def Threading(id):
print("%s - Hello threading" %id)
def thProc(id, sec):
while True:
Threading(id)
sleep(sec)
t1 = threading.Thread(target=thProc, args=("Test1",1))
t1.start()
위 코드는 1초마다 Test1 - Hello threading 를 출력하는 쓰레드 입니다.
t1 객체를 이용해 thProc을 실행해 주면 while 문을 통해 무한루프가 이루어지고 그에 따라서 Threading 함수가 실행되어 문자열이 출력 됩니다.
다만 while문 안에 sleep(sec) 이 있고, sec 에는 1이 전달되기 때문에 1초마다 출력되는 것입니다.
다음은 멀티쓰레드를 실행하는 소스를 삽입해 봅니다.
import threading
from time import sleep
def Threading(id):
print("%s - Hello threading" %id)
def thProc(id, sec):
while True:
Threading(id)
sleep(sec)
t1 = threading.Thread(target=thProc, args=("Test1",1))
t2 = threading.Thread(target=thProc, args=("Test2",3))
t1.start()
t2.start()
이번에는 3초마다 Test2 - Hello threading 을 출력하는 쓰레드도 생성했습니다.
실행화면은 아래와 같습니다.