Is this deque thread safe in python?

I cannot decide if the next deque is thread safe.
In short, I created a class with deque that displays its contents every 1 second in a new thread (therefore, it will not pause the main program while printing).
The deck is filled from the main thread, so basically there MUST be a chance of a collision.
HOWEVER, deque is populated using the class method, so essentially it is accessible from within the instance itself, therefore from the same stream.
Here's the simplified code:

import threading import time from collections import deque class MyQueue(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.q = deque() self.start() def run(self): # pop out queue items every 1 sec # (please ignore empty deque for now) while True: print self.q.popleft() time.sleep(1) def add_to_q(self, val): # this function is called from outside self.q.append(val) # main # fill the queue with values qu = MyQueue() for i in range(1:100): qu.add_to_q(i) 

So, although adding and removing elements from the queue takes place inside the instance, is there a risk that the add function is called from outside the instance?

EDIT:
Since I need to change the elements in my deque, I had to use Deque. What I'm doing is: roatate () for a given element, pop out, change, insert it back and rotate () back to its original position.
If I donโ€™t find a way to implement modifying elements in the queue, I will have to stick with Deque

+7
source share
3 answers

Deque is thread safe ( http://docs.python.org/library/collections.html#deque-objects ) for adding and popping from opposite sides. Below , the docs only mention that append () and popleft () are thread safe.

There is a stream implementation of the queue itself. Therefore, you should use it if you do not have strange requirements.

+13
source

For information, there is a Python ticket referenced by deque thread security ( https://bugs.python.org/issue15329 ).

Title "Clarify which deque methods are thread safe", bottom line:

Deque append (), appendleft (), pop (), popleft (), and len (d) operations are thread safe in CPython. Adding methods have DECREF at the end (for cases when maxlen is installed), but this happens after all structure updates have been made and invariants have been restored, so it is normal to treat these operations as atomic.

In any case, if you are not 100% sure and prefer performance reliability, just set Lock to print self.q.popleft() and self.q.append(val) ;)

+2
source

Queue module might be useful for you: http://docs.python.org/library/queue.html

0
source

All Articles