Queue.Queue vs. collections.deque

前端 未结 7 1374
眼角桃花
眼角桃花 2020-11-29 15:26

I need a queue which multiple threads can put stuff into, and multiple threads may read from.

Python has at least two queue classes, Queue.Queue and collections.dequ

7条回答
  •  -上瘾入骨i
    2020-11-29 15:38

    If all you're looking for is a thread-safe way to transfer objects between threads, then both would work (both for FIFO and LIFO). For FIFO:

    • Queue.put() and Queue.get() are thread-safe
    • deque.append() and deque.popleft() are thread-safe

    Note:

    • Other operations on deque might not be thread safe, I'm not sure.
    • deque does not block on pop() or popleft() so you can't base your consumer thread flow on blocking till a new item arrives.

    However, it seems that deque has a significant efficiency advantage. Here are some benchmark results in seconds using CPython 2.7.3 for inserting and removing 100k items

    deque 0.0747888759791
    Queue 1.60079066852
    

    Here's the benchmark code:

    import time
    import Queue
    import collections
    
    q = collections.deque()
    t0 = time.clock()
    for i in xrange(100000):
        q.append(1)
    for i in xrange(100000):
        q.popleft()
    print 'deque', time.clock() - t0
    
    q = Queue.Queue(200000)
    t0 = time.clock()
    for i in xrange(100000):
        q.put(1)
    for i in xrange(100000):
        q.get()
    print 'Queue', time.clock() - t0
    

提交回复
热议问题