Conditional-based thread-safe priority queue (implemented in python) and conditionpython
Condiftion can be understood as an advanced feature. It provides more advanced features than Lock and RLock, allowing us to control complicated thread synchronization problems. Threadiong. Condition maintains a wretched object internally (RLock by default). It can be passed as a parameter when a Condigtion object is created. Condition also provides the acquire and release methods, which have the same meaning as the wretched acquire and release methods. In fact, it is just a simple method to call the corresponding methods of the internal wretched objects. Based on this synchronization primitive, I implemented a simple thread-safe priority queue:
Import heapqimport threading # import timeclass Item: def _ init _ (self, name): self. name = name def _ repr _ (self): return 'item ({! R })'. format (self. name) class PriorityQueue: def _ init _ (self): self. _ queue = [] self. _ index = 0 self. mutex = threading. lock () self. cond = threading. condition () def push (self, item, priority): self. cond. acquire () heapq. heappush (self. _ queue, (-priority, self. _ index, item) # store a triple. The default structure is the small top heap self. _ index + = 1 self. cond. every y () # Wake up a suspended thread self. cond. release () def pop (self): self. cond. acquire () if len (self. _ queue) = 0: # When the number of data in the queue is 0, it is not difficult to block the thread and implement the thread-Safe Container. It is not difficult to understand the synchronization primitive mechanism, design the logic sequence of program execution (where blocking occurs and where wake up) self. cond. wait () # The wait method releases the internal lock and the thread is suspended. It knows that the notification is received or timed out. When the thread is awakened and re-occupied, the program continues to execute else: x = heapq. heappop (self. _ queue) [-1] # output self in reverse order. cond. release () return xdef test1 (p, item, index): for I in range (3): p. push (Item (item), index) def test2 (p): for I in range (3): print (p. pop () if _ name _ = '_ main _': p = PriorityQueue () t1 = threading. thread (target = test1, args = (p, 'foo', 1) t3 = threading. thread (target = test1, args = (p, 'bar', 2) t4 = threading. thread (target = test1, args = (p, 'login', 28) t2 = threading. thread (target = test2, args = (p,) t5 = threading. thread (target = test2, args = (p,) t6 = threading. thread (target = test2, args = (p,) t1.start () t2.start () t1.join () t2.join () t3.start () t5.start () t3.join () t5.join () t4.start () t6.start () t4.join () t6.join ()
I have also implemented a priority queue Based on event thread security. For more information, see <condition-based thread security priority queue (python implementation)>