Good way to create a lock, zero queue in Python

In Java, there is java.util.concurrent.SynchronousQueue , a queue without storage capacity. Topics trying to put / get a value are always blocked until another thread tries to get / put a value, respectively.

What are some good ways to do the same in Python? That is, I want to transfer values ​​from a set of one or more threads to another set of one or more threads without a value that ever "belongs" to a thread in any group.

Python queue.Queue does not allow the use of length 0 by specifying a non-positive value for maximum capacity, creating an unlimited queue.

+8
java python multithreading concurrency
source share
2 answers

I have the feeling that the next city may be a dead end, but something like the next job?

 class SynchronousQueue(object): def __init__(self): self.ready_to_get = Queue(1) self.queue = Queue(1) def get(self): self.ready_to_get.put('ready', block=True) return self.queue.get(block=True) def put(self, item): self.ready_to_get.get(block=True) self.queue.put(item, block=True) 

A regular queue supports half of what you want (a getter waits on a stick), so we can try to do the opposite by blocking put until it starts receiving.

+2
source share

You can use Queue.join() and Queue.task_done() to lock until get() :

 class SynchronousQueue(object): def __init__(self): self.q = Queue(1) self.put_lock = RLock() def get(self): value = self.q.get(block=True) self.q.task_done() return value def put(self, item): with self.put_lock: self.q.put(item, block=True) self.q.join() 
+2
source share

All Articles