5

I have a threaded program consisting of a Consumer class and a Producer class. Currently, I use a Fifo queue.Queue in the implementation, where the producer puts the data at the end of the queue and the consumer gets it.

However, I would like to add a feature where, if necessary, the Consumer can put back the (perhaps slightly modified) item that it gets by putting it back at the front of the Queue (so that the next item returned by get is the item just added, like in a stack).

I know this is possible with deques, but I've read here that they are only thread-safe for append() and popleft(). For the purposes above I'll also need to use appendleft().

Is there a thread-safe data structure that has the features of a deque? If not, could I make the deque thread-safe by putting in my own locks whenever I use appendleft?

Victor Odouard
  • 1,345
  • 3
  • 15
  • 28

2 Answers2

8

Deque author here.

  • The operations you're interested in are all atomic.
  • The only non-atomic operations are: remove(), index(), count, and clear() due to equality tests which can make pure python callbacks or due to decrefs which can trigger arbitrary python code.

Hope this helps :-)

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

While some deque features are not thread safe, what you're trying to do should be.

From the docs:

Deques support thread-safe, memory efficient appends and pops from either side of the deque

fantabolous
  • 21,470
  • 7
  • 54
  • 51