Python Basic Learning log day9--thread queue

Source: Internet
Author: User

One: Thread Queu effect

In Python, a queue is the most common form of exchanging data between threads.

Queue two functions: one is decoupling, the other is improving efficiency

Two: Grammar

1) Class of the queue

CLA Ss  queue. queue
Class  queue. lifoqueue
class  queue. priorityqueue

The constructor for the priority queue. maxsize The maximum number of items that can be placed in the queue.

Once this size is reached, the insert will block until the queue item is consumed. The maxsize value is less than or equal to 0, indicating that the queue size is infinite.

2) Queue of two exceptions

exceptionqueue.Empty 当调一个队列是空的,时候调用get()或者get_nowait()会抛出阻塞

exceptionqueue.Full 当调一个队列是最大值,时候调用put()或者put_nowait()会抛出非阻塞

3) How to queue

  Queue. qsize() determine the queue size
  Queue. empty() #空返回真
  Queue. full() # full Reverse back True
  Queue. put(Item, Block=true, Timeout=none)
#给队列增加一个item. If the block is set to true and Timeout=none, the expression is blocked until the queue can put the item in.
If timeout= is set to a positive value, indicating the maximum number of seconds to block, or the item cannot be put in, it will throw queue. Full异常。
If block is false,item, it can't be thrown in. queue. Full。
   Queue. put_nowait( item) = =  Queue. put (item, block=false)
   Queue. get( block=true, timeout=none)
  #从队列中删除并返回一个item. If block is set to true, and timeout=none, the expression is blocked until the queue can take item.  
If timeout= is set to a positive value, indicating the maximum number of seconds to block, or not fetching the item, it will throw queue.Empty 异常。  
If block is false, it cannot be taken to the item to throw queue.Empty 

Queue.get_nowait () = = Queue.get (False)

Queue.task_done ()

  Queue. Task_done (), each time a data is got from the queue, when the related problem is handled, the method is finally called to indicate whether Q.join () stops blocking and lets the thread forward or exit;

  queue. Join (), blocking until the data in the queue is deleted or processed. Called once for each item in the queue.

There is still a problem with the producer-consumer model, because if the queue is initially empty, q.join () will stop blocking directly and then execute the subsequent statements;

If there are multiple consumers, there is no producer, and the queue begins to be a certain amount of data, it can be executed normally.

Three: Producer consumer model

Using producer and consumer patterns in concurrent programming can solve most concurrency problems. This mode improves the overall processing speed of the program by balancing the productivity of the production line and the consuming thread.

Why use producer and consumer models

In the world of threads, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. To solve this problem, the producer and consumer models were introduced.

What is the producer consumer model

The producer-consumer model solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, Balance the processing power of producers and consumers.

Four: Code

 

#-*-coding:utf-8-*-__author__='Shisanjun'ImportQueueImport TimeImportThreadingq=queue. Queue ()defproducer (name): forIinchRange (10):        Print("%s produced the bun%s ..."%(Name,i)) q.put (i)#add an item to the queueTime.sleep (1) Q.join () #阻塞 until the data in the queue is deleted or processedPrint("The buns are finished .")defConsumer (name): whileTrue:ifQ.qsize () >0:Print("%s ate bun%s ....."%(Name,q.get ())) Q.task_done ()##告知这个任务执行完了Time.sleep (1) P=threading. Thread (target=producer,args= ("QJJ",)) C=threading. Thread (target=consumer,args= ("LSJ",)) P.start () C.start ( )"""qjj production of steamed bun 0...LSJ ate bun 0.....qjj production of steamed bun 1...LSJ ate bun 1.....qjj production of steamed bun 2...qjj production of steamed bun 3...lsj to eat the steamed bun 2.....qjj production of steamed buns ATE steamed bun 3.....LSJ ate bun 4.....qjj production of steamed bun 5...lsj to eat the bun 5.....qjj production of the steamed bun 6...qjj production of steamed bun 7...lsj to eat the steamed bun 6.....qjj produced a bun 8...lsj ate 7. LSJ ate steamed bun 8.....QJJ produced bun 9...lsj ate buns 9 .... The buns are finished ."""

Python Basic Learning log day9--thread 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.