Thread란?

간단히 하나의 프로세스 내에 어떠한 작업을 수행하는 주체를 의미하고 하나의 프로세스에서 여러개의 작업을 동시에 진행시키고 싶을 때 쓰레드를 이용하면 된다.

아래 소스코드는 Thread와 Queue를 이용하여 데이터를 주고 받는 예제이다.

 

Queue란?

컴퓨터의 기본적인 자료 구조의 한가지로, 먼저 집어 넣은 데이터가 먼저 나오는 FIFO(First In First Out)구조로 저장하는 형식을 말한다.

 

[예제 소스]

from queue import Queue
import threading
import time

def push(q):
    print('Thread1 Start')
    q.put('Zero')
    q.put('One')
    q.put('Two')
    q.put('Three')
    q.put('Four')


def pop(q):
    print('thread2 Start')
    while True:
        test = q.get() #큐의 내용을 얻어옮
        if test:
            time.sleep(1)
            print(test)

if __name__ == "__main__":
    queue = Queue() #큐 생성
    thread1 = threading.Thread(target=push, args=(queue, )) #쓰레드 생성
    thread2 = threading.Thread(target=pop, args=(queue, )) #쓰레드 생성
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

[실행]

이 처럼 Thread1,2 가 실행되고 queue로 데이터를 주고 받음을 확인 할 수 있다.

+ Recent posts