반응형
Queue 클래스는 스레드끼리 정보를 교환해야 하는
멀티 스레드 프로그래밍 상황에서 유용하다고 문서 페이지에서도 나타내고 있다.
예전같으면(C++로 작성했다면) 뮤택스랑 세마포어, 큐가지고 했을 작업을
파이썬에서는 Queue 클래스를 갖고 처리할 수 있다.
Queue 클래스의 멤버 함수를 일일이 열거할 생각은 없고
청하갤과 Slack 봇을 만들면서 작성했던 간단한 구조를 적어두려고 한다.
필요에 따라서 문서 페이지를 참고 하도록 하자.
동작은 아래의 소스와 주석을 참고하면 되는데
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, Queue | |
import time | |
class Catcher(threading.Thread): # Thread Extends | |
def __init__(self, id, dataQueue): | |
threading.Thread.__init__(self) | |
self.id = id # for print | |
self.dataQueue = dataQueue # data queue | |
def run(self): | |
while True: # thread task | |
data = self.dataQueue.get() # queue element get | |
print("[" + str(self.id) + " : " + str(data) + "]") | |
self.dataQueue.task_done() # work done notify to queue | |
def main(): | |
StringQueue = Queue.Queue() # create queue | |
StringQueue.put(1) # put data | |
StringQueue.put(2) | |
cat1 = Catcher("A", StringQueue) # declare thread obj | |
cat1.setDaemon(True) | |
cat2 = Catcher("B", StringQueue) | |
cat2.setDaemon(True) | |
cat1.start() # thread start | |
cat2.start() | |
StringQueue.put(3) | |
StringQueue.put(4) | |
cat1.dataQueue.join() # wait for data queue empty | |
cat2.dataQueue.join() | |
if __name__ == "__main__": | |
main() |
- 5 line : Catcher 클래스는 스레드로 동작하기 위해 threading.Thread를 상속한다.
- 8 line : 출력에서 thread 구분을 위해서 사용하는 변수
- 11~12 line : Queue에 쌓인 데이터를 모두 처리할때 까지 동작하는 While True 무한 루프.
- 13 line : Queue에서 데이터를 get 한다. 만약 Queue에 데이터가 없으면 블럭(Block)된다.
(get 함수의 매개변수에 따라 동작은 변경할 수 있다. default로 block = True, timeout = None으로 되어 있을 뿐)
- 17 line : Queue 에다가 get 된 데이터가 모두 처리 되었다고 알린다.
내부적으로 처리되지 않은 작업의 카운터를 감소한다.
- main() 함수 : Queue를 만들고 스레드를 만들고 데이터를 put 한다음에 스레드를 시작.
- 37 line : Queue 의 모든 데이터가 처리 될 때까지 블럭 된다.
Queue의 put 함수가 불릴때면 처리할 작업 카운터는 증가하고 task_done 함수가 불릴때면 처리할 작업 카운트가 감소한다.
작업 카운터가 0가 되면(할일이 없으면) 이 블럭은 해제된다.
반응형
'python > python' 카테고리의 다른 글
파이썬(Python)-취미 프로그래밍, 취미 프로젝트의 시작. (2) | 2016.06.09 |
---|