본문으로 바로가기

파이썬 Queue 모듈 다루기

category Language/Python 2020. 7. 21. 01:11
 

queue — 동기화된 큐 클래스 — Python 3.7.8 문서

queue — 동기화된 큐 클래스 소스 코드: Lib/queue.py The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queu

docs.python.org

Queue 란?

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

 

기본 사용법

큐를 생성하여 put/get 으로 입출력을 할 수 있습니다.

import queue

data = [1, 2, 'a', 'b', [1,2,3], {'a':1, 'b':2}]

q = queue.Queue()

for d in data: 
    q.put(d)

print('queue size:', q.qsize())
for i in range(q.qsize()):
    print(f'data: {q.get()}, queue size: {q.qsize()}')
print('queue size:', q.qsize())
queue size: 6
data: 1, queue size: 5
data: 2, queue size: 4
data: a, queue size: 3
data: b, queue size: 2
data: [1, 2, 3], queue size: 1
data: {'a': 1, 'b': 2}, queue size: 0
queue size: 0

 

큐는 크기를 지정할 수 있습니다.

empty 는 큐가 비어있으면 True 를 반환하며, full 은 큐가 가득차면 True 를 반환합니다.

q = queue.Queue(2)

print(f'qsize: {q.qsize()}')
print(f'empty: {q.empty()} / full: {q.full()}')

q.put(1)
print(f'put data, qsize: {q.qsize()}')
print(f'empty: {q.empty()} / full: {q.full()}')

q.put(2)
print(f'put data, qsize: {q.qsize()}')
print(f'empty: {q.empty()} / full: {q.full()}')
queue size: 0
qsize: 0
empty: True / full: False
put data, qsize: 1
empty: False / full: False
put data, qsize: 2
empty: False / full: True