Multi-threading issues in the queue

Inter-thread communication queue

Inter-thread communication between different communication queues and queues the process used, the process queue is encapsulated in multiprocessing module can be introduced from the module, the communication between threads requires import queue queue individual modules, the module does not Threading package.

  • Queue:
    • Import: import queue
    • This can be used in the service industry, first in first out
    • Examples of objects: q = queue.Queue (num), num for controlling the size of the queue, how much data can be placed.
    • Into the data: q.put (data)
    • Data taken: q.get ()
    • Queue length, but had to put data: q.put_nowait (data), this will be reported anomaly: queue.Full. You can add exception handling, but because the data will be lost after using this method, it is not recommended to use this method.
    • There are no data taken: q.get_nowait (), which also reported abnormal: queue.Empty, exception handling can be set:
try:
    print(q.get_nowait())
except queue.Empty:
    # queue.Empty不是内置的错误,而是queue模块中的错误,可以直接使用模块.错误类型来调用
    print('队列中没有数据')
  • LifoQueue:
    • LIFO queue is called, but it is actually a stack
    • We will not use the service sector, for the development of this multi-algorithm
    • Import: from queue import LifoQueue
    • Examples of: lq = LifoQueue ()
    • Into the data: lq.put (data)
    • Data taken: lq.get (data)
  • PriorityQueue:
    • Priority queue
    • The procedure used for VIP members of the development
    • Import: from queue import PriorityQueue
    • Examples of: pri = PriorityQueue ()
    • Data placed: pri.put ((num, data)), note the tuples, the first parameter is the sequence number
    • Data taken: pri.get (), the data is acquired as the number of the acquired priority, the first-out number the smaller the number, the ASCII code ordering number is sorted, ordering is not a normal digital method.
from queue import PriorityQueue

pri = PriorityQueue()
pri.put((1, '福娃'))
pri.put((2, '奥运'))
pri.put((0, '五环'))
print(pri.get())
print(pri.get())
print(pri.get())

'''结果是:
(0, '五环')
(1, '福娃')
(2, '奥运')
'''

Guess you like

Origin www.cnblogs.com/ddzc/p/12470775.html