1

Is there a way to change values after they have been put into a queue? For instance, if I have a queue that has a couple variables in it, could I sum the first variable with some other value not in the queue? Would the best way to do this be something like:

x = queue.get()
queue.put(x+some_value)

Or is there a way to do it without removing the object from the queue first?

Jesse Rusak
  • 56,530
  • 12
  • 101
  • 102
user1423020
  • 275
  • 1
  • 4
  • 11
  • is there a particular reason you have to use a queue? why not use a list instead, then you can modify the values in place quite easily. – EEP Jul 11 '12 at 20:13

2 Answers2

1

You probably want shared values such as multiprocessing.Value, multiprocessing.Array, not queue. Queue doesn't allow it.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
1

A queue does not allow access in this way; you are asking to directly access an object which is still in the queue, which defeats the purpose of a queue.

I think what you might be looking for is a deque object to use instead of a queue (read about it here: http://docs.python.org/library/collections.html#collections.deque)

A deque object is thread-safe, and can behave like a queue while still allowing access directly to its members with an index value. However it's slower for random access unless you are accessing the left or right ends of the deque, so if I understood your question correctly this shouldn't be an issue in your case.

If however you do have a lot of random accesses to the deque, just use a multiprocessing.array instead.

Atra Azami
  • 2,215
  • 1
  • 14
  • 12
  • I'm not sure I understand what you mean. If it's run in different processes, the address space won't be shared and thus there's no cause for concern. Also, regarding your original question, I realized that Queue() has an internal Queue().queue which is essentially a deque object, which you can use to access the queue in the way you described in your original question. It's not recommended however; read more about it here: http://stackoverflow.com/questions/717148/python-queue-queue-vs-collections-deque – Atra Azami Jul 11 '12 at 21:57