Python

list vs Queue vs Deque 멀티쓰레딩 파이썬

jinmc 2021. 3. 9. 10:18
반응형

참고 : programmer.group/python-collections.deque-vs-queue.queue-vs-multiprocessing.queue.html 

 

Python collections.deque vs. Queue.Queue vs. multiprocessing.Queue

Generally speaking, multiprocessing.Queue is used when communication between processes is needed; Queue.Queue is used when communication between threads is needed in the same process; and collections.deque is usually used as a data structure in the same th

programmer.group

 

파이썬에서 멀티쓰레딩 프로그래밍을 할 때, 자료구조를 어떤 걸 사용해야 할까요?

가장 간단한 건, list를 사용하는 것일 겁니다.

하지만 list는 여러 문제점이 많습니다. 

 

stackoverflow.com/questions/6319207/are-lists-thread-safe

위의 스택오버플로우의 답변처럼, list는 thread-safe 하지만, 그 안에 있는 데이터는 그러지 못하기 때문에

race-condition이 발생하는 경우에는 내가 정말 하고자 하는 일을 하지 못한다고 합니다.

게다가, list의 안에있는 아이템들을 modify 하는 경우 list를 iterate하는 경우 예상치 못한 일들이 발생할 수도 있습니다.

다음 코드를 봅시다.

 

import time
  
lst = [1,2,3,4,5]
def rem_items(lst):
    for i in lst:
        #print(lst)
        time.sleep(1)
        lst.remove(i)
        print(lst)

rem_items(lst)

##[2, 3, 4, 5]
##[2, 4, 5]
##[2, 4]

 출력이 왜 이렇게 나올까요? 

다음 스택오버플로우를 보면 답이 나옵니다.

stackoverflow.com/questions/66202590/removing-item-in-list-in-python3-as-a-for-loop-weird-behavior

 

그럼 deque와 queue는 어떨까요?

deque를 사용하는건 상관이 없지만, 멀티쓰레딩을 하는 경우에는 주로 Queue.queue를 사용하고

또 multiprocessing에 사용하는 queue도 따로 있다고 합니다.

 

반응형

'Python' 카테고리의 다른 글

Python time 라이브러리 활용한 로그 찍기  (0) 2022.05.10
list 에서 Queue로 옮기기  (0) 2021.03.09