search
HomeBackend DevelopmentPython TutorialDeep understanding of coroutine functions in python

Deep understanding of coroutine functions in python

Apr 14, 2018 am 11:16 AM
pythonfunctioncoroutine

The content of this article is to share with you an in-depth understanding of the coroutine function in python, which has a certain reference value. Friends in need can refer to it

Concept:

According to the definition given by Wikipedia, "Coroutines are computer program components that generate subroutines for non-preemptive multitasking. Coroutines allow different entry points to pause or start program execution at different locations." From a technical perspective, "a coroutine is a function that you can pause execution of." If you understand it as "just like a generator", then you're thinking right.

Coroutine, also known as micro-thread, looks like a subroutine, but it is different from a subroutine. During the execution process, it can interrupt the current subroutine. After the program executes other subroutines, it returns to execute the previous subroutine, but its related information is still the same as before.

Coroutines are different from threads. Threads are preemptive scheduling, while coroutines are collaborative scheduling. Coroutines need to do their own scheduling.
Subroutine calls always have one entrance and one return, and the calling sequence is clear. The calling of coroutines is different from subroutines. Coroutines also look like subprograms, but during execution, they can be interrupted inside the subprogram, then switch to executing other subprograms, and then return to continue execution at the appropriate time.

Advantages of coroutines:

  • The advantage of coroutines is extremely high execution efficiency. Because subroutine switching is not thread switching, but is controlled by the program itself, there is no overhead of thread switching. Compared with multi-threading, the greater the number of threads, the more obvious the performance advantages of coroutines. It is very suitable for performing coroutine multitasking.

  • Coroutines have no thread safety issues. A process can have multiple coroutines at the same time, but only one coroutine is active, and the activation and dormancy of coroutines are controlled by programmers through programming, not by the operating system.

Generator implements coroutine principle

Example:

def func(n):
    index=0
    if index<=n:
        c=yield 1
        print("task------{}".format(c))
        index+=1f=func(3)
n=next(f)
print(n)try:
    n=f.send(5)#程序就直接结束了
    print("n是{}".format(n))except StopIteration as e:    pass
输出打印:1task------5

Explanation:

  • Obviously func is a generator, and the send method has a parameter that specifies the return value of the last suspended yield statement.

  • send requires exception handling.

  • In general, the only difference between the send method and the next method is that when executing the send method, the return value of the last pending yield statement will first be set through parameters to achieve Interaction with generator methods. However, it should be noted that before a generator object executes the next method, since no yield statement is suspended, an error will be reported when executing the send method.

  • When the parameter of the send method is None, it is completely equivalent to the next method.

The generator implements the producer and consumer patterns:

def cunsumer():
    while True:
        n=yield 3
        if not n:            return
        print(&#39;cunsumer{}&#39;.format(n))def product(c):
    c.send(None)
    n=0
    while n<5:
        n=n+1
        r=c.send(n)
        print("product{}".format(r))
    c.close()
c=cunsumer()
product(c)
打印:
cunsumer1
product3
cunsumer2
product3
cunsumer3
product3
cunsumer4
product3
cunsumer5
product3

Explanation:

Execute first in the producer The purpose of c.send(None) is to let the consumer hang up first, and then use send to pass the value. The first time 1 is passed, the consumer prints 1, and the producer prints r which is the value after the consumer's yield.

Introduction of greenlet

Although CPython (standard Python) can implement coroutines through generators, it is not very convenient to use.

At the same time, Stackless Python, a derivative of Python, implements native coroutines, which is more convenient to use.

So, everyone began to take out the coroutine code in Stackless and make it into a CPython expansion package.

This is the origin of greenlet, so greenlet is a C extension library that implements native coroutines at the bottom.

Code description:

from greenlet import greenletimport randomimport timedef Producer():
    while True:
        item = random.randint(0,10)
        print("生产了{}".format(item))
        c.switch(item)#切换到消费者,并将item传入消费者
        time.sleep(1)def consumer():
    print(&#39;我先执行&#39;)    #p.switch()
    while True:
        item = p.switch()#切换到生产者,并且等待生产者传入item
        print(&#39;消费了{}&#39;.format(item))
c = greenlet(consumer)#将一个普通函数变成一个协程p = greenlet(Producer)
c.switch()#让消费者先进入暂停状态(只有恢复了才能接收数据)

Value of greenlet:

  • High-performance native coroutine

  • Explicit switching with clearer semantics

  • Wrap functions directly into coroutines and maintain the original code style

gevent coroutine

Although we have a callback programming model based on epoll, it is difficult to use.

Even though we can make complex encapsulation with generator coroutine to simplify programming difficulty.
But there is still a big problem: encapsulation is difficult, and the existing code must be almost completely rewritten

gevent, by encapsulating the two libraries libev (based on epoll) and greenlet.
Help us encapsulate it and allow us to use coroutines in a thread-like manner.

So that we can make full use of the power of epoll and coroutines without rewriting the original code.

Code diagram:

from gevent import monkey;monkey.patch_all()#会把python标准库当中一些阻塞操作变成非阻塞import geventdef test1():
    print("11")
    gevent.sleep(4)#模拟爬虫请求阻塞
    print("33")def test2():
    print("22")
    gevent.sleep(4)
    print("44")
gevent.joinall([gevent.spawn(test1),gevent.spawn(test2)])#joinall 阻塞当前协程,执行给定的greenlet#spawn 启动协程,参数就是函数的名字

The value of gevent:

Switch to another coroutine to continue execution when it encounters blocking !

  • Use epoll-based libev to avoid blocking.

  • Use efficient coroutines based on gevent to switch execution.

  • Only switches when encountering blocking. There is no round-robin overhead or thread overhead.

gevent implements concurrent server

from gevent import monkey;monkey.patch_all()  #建议放在首行,会把python标准库当中一些阻塞操作变成非阻塞import geventimport socket


server=socket.socket()
server.bind((&#39;&#39;,6666))
server.listen(5)
print("开始监听")def readable(con,addr):
    print("客户端{}接入".format(addr))    while True:
        data=con.recv(1024)        if data:
            print(data)        else:
            con.close()            breakwhile True:
    con,addr=server.accept()
    gevent.spawn(readable,con,addr)#将readable函数变为协程,并且把con和addr传入其中。

gevent coroutine communication

gevent also has its own queue. The usage is basically the same as threading.

Producer and consumer patterns based on gevent and queue

from gevent import monkey;monkey.patch_all()import geventfrom gevent.queue import Queueimport randomdef producter(queue):
    while True:
        item=random.randint(0,99)
        print(&#39;生产了{}&#39;.format(item))
        queue.put(item)
        gevent.sleep(1)def comuser(queue):
    while True:
        item=queue.get()
        print(&#39;消费了{}&#39;.format(item))
queue=Queue()
p=gevent.spawn(producter,queue)
c=gevent.spawn(comuser,queue)
gevent.joinall([p,c])
打印:
生产了33消费了33生产了95消费了95生产了92消费了92...


相关推荐:

python中多进程+协程的使用

python中协程

Python 协程的详细用法和例子

python 协程示例

The above is the detailed content of Deep understanding of coroutine functions in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.