본문 바로가기

Backend/Python

첫코딩 : 스레드(thread)

thread(스레드) : 실, 가닥, 줄기

threading(스레싱) : 조각조각 나눠서 따로 사용하는 행위

multi threading(멀티 스레딩) : 컴퓨터가 업무를 동시에 하는 것이 아니라 여러가지 업무를 번갈아가며 하는데, 

우리 눈에는 마치 동시에 하는 것처럼 보인다.

import threading # threading 패키지 불러오기


class count(threading.Thread): # Thread 클래스 상속받기

    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run(self): # 호출 이름 : run 
        for i in range(0, 5):
            print(self.name, i)


first = count('1st')
second = count('2nd')

first.start() # 메서드 이름 : start 
second.start()

# 결과값 (숫자가 섞이게 됨)

1st 0
1st 1
2nd 0
1st 2
1st 3
2nd 1
1st 4
2nd 2
2nd 3
2nd 4

상속받은 threading.Thread 클래스는 start()메서드를 실행하면 클래스의 메서드 중 run() 메서드를 찾아 실행

run()은 메서드를 단순히 실행하지 않고 스레딩한 후 실행함.