A synchronized, thread-safe queue class is provided in the Python queue module, including FIFO (first-in, first-out) queue Queue,lifo (back-in-first-out) queue Lifoqueue, and priority queue priorityqueue. These queues implement the lock primitive and can be used directly in multiple threads. Queues can be used for synchronization between threads.
Common methods in the queue module:
- Queue.qsize () returns the size of the queue
- Queue.empty () returns True if the queue is empty, and vice versa false
- Queue.full () returns True if the queue is full, otherwise false
- Queue.full corresponds to maxsize size
- Queue.get ([block[, timeout]]) Get queue, timeout wait time
- Queue.get_nowait () quite queue.get (False)
- Queue.put (item) write queue, timeout wait time
- Queue.put_nowait (item) quite Queue.put (item, False)
- Queue.task_done () After completing a work, the Queue.task_done () function sends a signal to the queue that the task has completed
- Queue.join () actually means waiting until the queue is empty before performing another operation
#Coding=utf-8#!/usr/bin/pythonImportQueueImportThreadingImportTimeexitflag=0classMyThread (Threading. Thread):def __init__(self, ThreadID, name, Q): Threading. Thread.__init__(self) self.threadid=ThreadID Self.name=name Self.q=QdefRun (self):Print "starting"+self.name process_data (self.name, SELF.Q)Print "Exiting"+Self.namedefProcess_data (ThreadName, q): while notExitFlag:queueLock.acquire ()if notworkqueue.empty (): Data=Q.get () queuelock.release ( )Print "%s Processing%s"%(threadname, data)Else: Queuelock.release () time.sleep (1) Threadlist= ["Thread-1","Thread-2","Thread-3"]namelist= [" One"," Both","three"," Four","Five"]queuelock=Threading. Lock () WorkQueue= Queue.queue (10) Threads=[]threadid= 1#Create a new thread forTnameinchThreadlist:thread=MyThread (ThreadID, Tname, WorkQueue) Thread.Start () threads.append (thread) ThreadID+ = 1#populating queuesQueuelock.acquire () forWordinchnameList:workQueue.put (Word) queuelock.release ()#wait for the queue to empty while notworkqueue.empty ():Pass#notifies the thread that it is time to exitExitflag = 1#wait for all threads to complete forTinchThreads:t.join ()Print "Exiting Main Thread"
Python multithreading--priority queuing (queue)