I can't decide whether the following deque is thread-safe.
In short, I've created a class with a deque that displays its contents every 1 sec in a new thread (so it won't pause the main program while printing).
The deque is filled from the main thread, so basically there SHOULD be a chance of collision.
HOWEVER, the deque is filled using a class method, so essentially it is accessed from within the instance itself, therefore from the same thread.
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 items from queue take place inside the instance, is there a risk due to the adding function being called from outside the instance?
EDIT:
Since I need to modify items in my deque, I had to use Deque. What I do is: roatate() to the given item, pop it out, modify, push it back in and rotate() it back to its original position.
Unless I find a way of implementing modifying items in a Queue, I'll have to stick to Deque
Python queue is a built in library that allows you to create a list that uses the FIFO rule, first in first out. Python deque uses the opposite rule, LIFO queue, or last in first out. Both operate on stacks and queues. When you're working in Python, you may want to create a queue of items instead of a list.
A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.
A list is one of the main workhorses in almost every Python script, yet, in some cases, opting for deques can lead to much faster performance.
Deques are sequence-like data types designed as a generalization of stacks and queues. They support memory-efficient and fast append and pop operations on both ends of the data structure. Note: deque is pronounced as “deck.” The name stands for double-ended queue.
Deque is thread-safe (http://docs.python.org/library/collections.html#deque-objects) for appends and pops from opposite sides. Beneath here, the docs only mention that append() and popleft() are thread-safe.
There is a thread-safe implementation of the Queue itself. So you should be using it unless you have some strange requirements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With