12.2. Multi-threaded communication: Queue

Source: Internet
Author: User

Queue
    • What is a queue: a special structure, similar to a list. But just like in a queue, once the elements in the queues are removed, they are removed from the queue.
    • Communication between threads can be done using queue queues
    • How the thread uses the queue. Queue "There are other types of objects to talk about below" to communicate:
      • 1. Create a Queue object: Object =queue. Queue (x), X is the queued capacity, X can not be filled, the default is no capacity limit,
      • 2.get () allows a thread to get an element from the queue, if the queue is empty, get waits, get can set the timeout parameter, which is the wait time
      • 3.put () can put an element into the queue "the default queue is first-in, first-out, first-placed elements will be taken out first", if the queue is full, put will wait, put can set the timeout parameter, which is the wait time

The following example is: Sender thread sends diameter to Recvder thread, Recvder calculates perimeter "

ImportThreading,time,queue,randomdefSender ():#Sender Send diameter     whiletrue:x=random.randint (1,10)        Print("Send done:", X) q.put (x)#put a random number on each secondTime.sleep (1)#Put a A in every seconddefRecvder ():#recvder Calculate Perimeter    whiletrue:x=Q.get ()Print("recv Done:", x*3.14)#Take out an element every second and calculate the resultTime.sleep (1) Q=queue. Queue () T1=threading. Thread (target=sender) T2=threading. Thread (target=recvder) T1.start () T2.start () T1.join () T2.join ()

    • The Queue object already contains the necessary locks, so do not worry about errors
ImportThreading,time,queue,randomdefSender ():#Sender Send diameter     whiletrue:x=random.randint (1,10)        Print("Send done:", X) q.put (x)#put a random number on each secondTime.sleep (1)#Put a A in every seconddefRecvder ():#recvder Calculate Perimeter    whiletrue:x=Q.get ()Print(Threading.current_thread (),"recv Done:", x*3.14)#Take out an element every second and calculate the resultTime.sleep (2) Q=queue. Queue () T1=threading. Thread (target=sender) T2=threading. Thread (target=recvder) T3=threading. Thread (target=recvder) T1.start () T2.start () T3.start () t1.join () t2.join () T3.join ()

Note:

Queues can have capacity limits:

Settings for timeout:

Other related functions of the queue "set Q as a queue object":
    • Q.qsize (): Returns the number of elements in the current queue
    • Q.empty (): Determines whether the queue is empty, returns a Boolean value
    • Q.full (): Determines whether the queue is full, returns a Boolean value

    • Q.get_nowait (): Use Get () directly, if there is no element in the queue, then it will block wait, after using get_nowait (), if there is no element in the queue, then an error will be
    • Q.put_nowait (): Direct use put (), if the queue is full, then will block wait, using put_nowait (), if the queue is full, then will be an error

    • Q.task_done (): After completing a work, the Task_done () function sends a signal to the queue that the task has completed "functions similar to: There is a single-plank bridge that can only load one person, a came to find B in the bridges, so a can not on the bridge, he is waiting, wait until B after the bridge shout him, He knew B had finished the bridge. "Q.task_done is mainly used in conjunction with Q.join ()
    • Q.join (): actually means waiting until the queue is empty, and then performing another operation "you need to call Task_done after each get, until all the queues are empty, then the join below is executed"
ImportThreading,queue,time"""This example is: Manufacturers with the driver agreed, the production of 3, the driver to pull, and a pull away, only when 3 are pulled away, manufacturers continue to produce"""defProducer ():#Manufacturers     whileTrue: forIinchRange (3): Q.put (i) start_time=time.time () q.join ( )##结果显示join这里堵塞住了厂家线程        Print("Wait Time:", Time.time ()-start_time)#used to test for blockage, proving not because the driver's sleep jam is runningdefDriver ():#Old driver     whileTrue: forIinchRange (3):            Print(Q.get ()) Q.task_done ()Print("") Time.sleep (2) Q=queue. Queue () T1=threading. Thread (target=producer) T2=threading. Thread (target=driver) T1.start () T2.start () T1.join () T2.join ()

In the queue, there are other queues, and here are some common ones:
    • A queue is a first-in, first-out line:

    • The Lifoqueue is the back-in-first-out queue:

    • Priorityqueue is the order in which elements are determined by the precedence specified when the element is loaded:
      • Create method: Queue Object =queue. Priorityqueue ()
      • Priority is small priority, but cannot be mixed, str can only be sorted with str, int can only be sorted with int
      • The priorityqueue put parameter is a tuple in the format: Queue object. Put ((priority, data))

    • The deque is a double-ended queue that allows first-in, first-out and back-to-back, i.e. both ends can be
      • Because the double-ended queue is not practical, and the list is not very different, do not elaborate here, we can refer to: https://www.cnblogs.com/zhenwei66/p/6598996.html

12.2. Multi-threaded communication: Queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.