Example Analysis of basic queue Operation and Multithreaded queue in python
This article is about the basic operation of queues in python and the sample analysis of multithreaded queues. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Queue basic operation from queue import Queueq = Queue (5) # create a queue with a capacity of 5. If you give a number less than 0, the queue is listed as an infinite size. (this is the official explanation, actually it is not infinite size, but memory related) # Storage data q.put (123) # numeric q.put ('hello worldview') # string q.put (['hello',' world']) # list q.put (('hello',' world')) # tuple q.put ({'hello':' world'}) # Dictionary # if you try to store the sixth one again Blocking occurs because the capacity is set to q.put ({'hello':' python'})
Take out the value from the queue:
Print (q.get ()) print (q.get) print (q.get ()) print (q.get ()) print (q.get ())
As shown in the figure, five values are taken out in turn. Queue queues follow first-in, first-out.
Q.put_nowait ()
The q.put_nowait () method can add content to the queue without hindrance, reporting an error immediately if the queue is full, without waiting (that is, no blocking).
Q.get_nowait ()
The q.get_nowait () method can fetch content from the queue without hindrance, and if the queue is empty, it will report an error directly without waiting.
The specific use is no longer an example.
View the current queue size
Q.qsize ()
Print (q.qsize ()) print (q.get ()) print (q.qsize () print (q.get ()) print (q.qsize ())
As shown in the figure, each time a value is taken out, the queue size is reduced by one. Similarly, each value stored in the queue size will be increased by one.
Q.full ()
Determine whether the queue is full.
Q.empty ()
Determine whether the queue is empty.
Print (q.full ()) print (q.get ()) print (q.get ()) print (q.full ()) print (q.empty ()) print (q.get ()) print (q.empty ()) II, multithreaded queue from queue import Queueimport threadingimport time# storage value Store a value of def set_value (Q): num = 0 while True: q.put (num) num + = 1 time.sleep (1) # every second Take def get_value (Q): while True: print (q.get ()) if _ _ name__ ='_ _ main__': Q = Queue (4) T1 = threading.Thread (target=set_value, args= (Q,)) T2 = threading.Thread (target=get_value, args= (Q,)) t1.start () t2.start ()
The program starts to run, storing and taking values at the same time
This idea is applied to crawlers, that is, access and obtain data while downloading data.
Thank you for reading! On the "python queue basic operation and multithreaded queue example analysis" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!