GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — PythonAdvanced/docs/14.协程-greenlet.md at master · feixiao/PythonAdvanced

Expand file tree

/

14.协程-greenlet.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
75 lines (50 loc) · 1.04 KB
/

14.协程-greenlet.md

Copy path

File metadata and controls

75 lines (50 loc) · 1.04 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

greenlet

为了更好使用协程来完成多任务,python中的greenlet模块对其封装,从而使得切换任务变的更加简单

一.安装和使用greenlet

1.安装

sudo pip3 install greenlet

2.使用

结构:

from greenlet import greenlet
def 函数名1(参数列表):
    代码1
    变量名2.switch()

def 函数名2(参数列表):
    代码2
    变量名1.switch()
    
变量名1 = greenlet(函数名1)
变量名2 = greenlet(函数名2)

变量名1.switch()

demo:

import time
from greenlet import greenlet


def fun1():
    while True:
        print("___func1执行了___")
        g2.switch()
        time.sleep(0.5)


def func2():
    while True:
        print("___func2执行了___")
        g1.switch()
        time.sleep(0.5)


g1 = greenlet(fun1)
g2 = greenlet(func2)


# 切换到gr1中运行
g1.switch()

运行结果:

___func1执行了___
___func2执行了___
___func1执行了___
___func2执行了___
___func1执行了___
___func2执行了___
....省略....
You are visitor 01402605 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.