协程应用-yiled-greenlet-gevent

一、yiled

import time


# 任务1
def work1():
    while True:
        print("work1_start")
        time.sleep(0.5)
        yield
        time.sleep(0.5)
        print("work1_end")


    # 任务2


def work2():
    while True:
        print("work2_start")
        time.sleep(0.5)
        yield
        time.sleep(0.5)
        print("work2_end")



w1 = work1()
w2 = work2()
while True:
    next(w1)
    next(w2)

二、greenlet

import time

import greenlet


# 任务1
def work1():
    while True:
        print("work1_start")
        time.sleep(0.5)
        w2.switch()


    # 任务2


def work2():
    while True:
        print("work2_start")
        time.sleep(0.5)
        w1.switch()
       

w1 = greenlet.greenlet(work1)
w2 = greenlet.greenlet(work2)

while True:
    w1.switch()

三(1)、gevent:不带monkey

因为没有使用monkey,所以系统里直接使用time.sleep无法生效。只能使用包自带的gevent.sleep

import time
import gevent


# 任务1
def work1(w):
    print(w)
    gevent.sleep(1)
    print("w1 end")


# 任务2
def work2(w):
    print(w)
    gevent.sleep(1)
    print("w2 end")


w1 = gevent.spawn(work1, "work1_start")
w2 = gevent.spawn(work2, "work2_start")

w1.join()
w2.join()

三(2)、gevent:带monkey

import gevent
import time
from gevent import monkey

# 打补丁,让gevent框架识别耗时操作,比如:time.sleep,网络请求延时
monkey.patch_all()


# 任务1
def work1(w):
    print(w)
    time.sleep(1)
    print("w1-end")


# 任务1
def work2(w):
    print(w)
    time.sleep(1)
    print("w2-end")


if __name__ == '__main__':
    w1 = gevent.spawn(work1, "w1")
    w2 = gevent.spawn(work2, "w2")
    #阻塞等待两个协程执行完毕
    gevent.joinall([w1, w2])

三(3) sock协程方式

import gevent
from gevent import monkey

# 次序为:先放monkey,后放需打补丁的引入
monkey.patch_socket()
from socket import *

# 打补丁,让gevent框架识别耗时操作,比如:time.sleep,网络请求延时


server_addr = ("127.0.0.1", 8080)
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(server_addr)
s.listen(3)


def handle(c):
    while True:
        data = c.recv(128)
        if not data:
            break
        print(data)
        c.send(b"ok")


while True:
    c, addr = s.accept()
    print("connect from ", addr)
    gevent.spawn(handle, c)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值