The "Python" process implements the producer consumer model

Source: Internet
Author: User

The implementation of the association is collaborative rather than preemptive, which is the biggest difference from the process thread. In Python, the use of yield and send can make it easy to implement a co-process.

First review the generator.

If a function uses the yield statement, then it is a generator function. When this function is called, it returns an iterator. When the first call to __next__ () occurs, the generator function body begins execution and terminates when the yield expression is encountered.

The yield value statement returns none when using the __next__ () method, and yield value returns V when the Send (V) method is used. In other words, the __next__ () method is equivalent to the Send (None) method

1 defconsumer ()2      whileTrue:3line =yield#Line receives the return value of the yield expression! 4         Print(Line.upper ())5 6 7 defproductor ():8With open ('Text.txt') as file:9          forI, lineinchEnumerate (file):Ten             yield Line One             Print("{0} lines". Format (i)) A  -  -c =consumer () theC.__next__()#手动启动生成器,Note that the python3.x is not C.next () -  forIinchproductor (): -C.send (i)

Reference: 91 recommendations for improving Python procedures recommendations 66, 67

The "Python" process implements the producer consumer model

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.