SoFunction
Updated on 2024-11-17

Python multi-threaded communication queue queue usage example analysis

This article is an example of Python multi-threaded communication queue queue usage. Shared for your reference, as follows:

queue:
  • What is a Queue: is a special structure, similar to a list. But just like a queue, once the elements in the queue are taken out, then they are removed from the queue.
  • Communication between threads can be done using the queue queue
  • How threads communicate using [there are other types of objects covered below]:
    • 1. Create a Queue object:object = (x).x is the queue capacity, x can be left out, there is no capacity limit by default.
    • () enables a thread to fetch an element from the queue.If the queue is empty, get will wait. get can set the timeout parameter, which is the waiting time.
    • () puts an element into the queue.The default queue Queue is first-in-first-out, and the elements that are put in first will be taken out first.], if the queue is full, put will wait, put can set the timeout parameter, this is the waiting time
    • image

The following example: the sender thread sends the diameter to the recvder thread, and the recvder calculates the circumference.

import threading,time,queue,random
def sender():#sender sends diameter
 while True:
 x=(1,10)
 print("send done:",x)
 (x)# Put in a random number every second
 (1)# Put in an a every second

def recvder():#recvder calculates perimeter
 while True:
 x=()
 print("recv done:",x*3.14)# Take out an element every second and compute the result
 (1)

q=()
t1=(target=sender)
t2=(target=recvder)

()
()

()
()
  • The Queue object already contains the necessary locks, so don't worry about errors!
import threading,time,queue,random
def sender():#sender sends diameter
 while True:
 x=(1,10)
 print("send done:",x)
 (x)# Put in a random number every second
 (1)# Put in an a every second

def recvder():#recvder calculates perimeter
 while True:
 x=()
 print(threading.current_thread(),"recv done:",x*3.14)# Take out an element every second and compute the result
 (2)


q=()
t1=(target=sender)
t2=(target=recvder)
t3=(target=recvder)

()
()
()

()
()
()

Notes:

Queues can have capacity limits:

image

Timeout settings.

image


Other related functions of the queue [set q to be a Queue object]:

  • (): return the number of elements in the current queue
  • (): determine whether the queue is empty, return a boolean value
  • (): determine whether the queue is full, return a boolean value
  • q.get_nowait(): use get() directly, if there is no element in the queue, then it will block and wait.After using get_nowait(), if there are no elements in the queue, then an error is reported
  • q.put_nowait(): use put() directly, if the queue is full, then it will block and wait.After using put_nowait(), if the queue is full, then an error is reported
  • q.task_done() :After completing a job, the task_done() function sends a signal to the queue where the task has been completed [functionally similar:There is a log bridge that can only support one person, A comes and finds that B is on the bridge, so A can't get on the bridge, so he waits and calls out to him when B has finished crossing, and he realizes that B has finished crossing the bridge.][q.task_done is mainly used in conjunction with ()]
  • (): In practice, this means waiting until the queue is empty before performing another operation [task_done needs to be called after each get until all the queues are empty, at which point the following join will be performed].
import threading,queue,time
"""
The example is: the manufacturer agrees with the driver to produce a full production of 3 before the driver comes to pull them, the
And one by one, only when all 3 are pulled, the manufacturer continues production
"""
def producer():# Manufacturers
 while True:
 for i in range(3):
  (i)
 start_time=()
 ()## results show join here is blocking the manufacturer threads
 print("wait time:",()-start_time)# Used to test for clogging and prove that it's not the driver's SLEEP that's clogging the run


def driver():#Veteran drivers
 while True:
 for i in range(3):
  print(())
  q.task_done()
 print("")
 (2)


q=()
t1=(target=producer)
t2=(target=driver)

()
()

()
()

image


queue in addition to Queue, there are other queues, the following are commonly used:

  • Queue is a first-in-first-out queue:

image

  • LifoQueue, on the other hand, is a last-in-first-out queue

image

  • PriorityQueue is used to determine the order in which elements come out by the priority specified when loading them:
    • Creation method: queue object = ()
    • Priority is small first, but can not be mixed sort, str can only be sorted with str, int can only be sorted with int.
    • The arguments to PriorityQueue's put are tuples in the format: queue object.put((priority, data))

imageimage

  • deque is a double-ended queue that allows both first-in-first-out and last-in-last-out, i.e., both ends can go out
    • Since double-ended queues are of little utility, they are practically indistinguishable from lists, which will not be elaborated here:///article/

Readers interested in more Python related content can check out this site's topic: theSummary of Python process and thread manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorials》、《Python + MySQL Database Programming Tutorial for Beginnersand theSummary of common database manipulation techniques in Python

I hope that what I have said in this article will help you in Python programming.