python协程简易补充

本文通过Python代码示例介绍了协程的同步和异步执行方式,使用gevent库创建并发任务。在同步示例中,任务按顺序执行;而在异步示例中,所有任务同时进行。此外,还展示了如何使用协程实现简单的网络通信,包括服务器监听和客户端发送接收数据。
摘要由CSDN通过智能技术生成


前言

补充上篇中python中yield和协程的协程内容


提示:以下是本篇文章正文内容,下面案例可供参考

一、协程的同步和异步

实例一(同步)

#! /usr/bin/python
# -*-coding: UTF-8 -*-
from gevent import monkey;monkey.patch_all()#如果不用gevent.sleep的话
import gevent
import time

from greenlet import greenlet

def task(pid):
    time.sleep(0.5)
    print("task %s is done"%pid)
def main():
    #同步
    for i in range(10):
        task(i)


    pass

if __name__=='__main__':
    main()

运行结果为:

task 0 is done
task 1 is done
task 2 is done
task 3 is done
task 4 is done
task 5 is done
task 6 is done
task 7 is done
task 8 is done
task 9 is done

Process finished with exit code 0

实例二(异步)

#! /usr/bin/python
# -*-coding: UTF-8 -*-
from gevent import monkey;monkey.patch_all()#如果不用gevent.sleep的话
import gevent
import time

from greenlet import greenlet

def task(pid):
    time.sleep(0.5)
    print("task %s is done"%pid)
def main():
    #异步
    g_l = [gevent.spawn(task,i) for i in range(10)]
    gevent.joinall(g_l)
    print("main done")



    pass

if __name__=='__main__':
    main()

运行结果为:

task 0 is done
task 1 is done
task 2 is done
task 3 is done
task 4 is done
task 5 is done
task 6 is done
task 7 is done
task 8 is done
task 9 is done
main done

Process finished with exit code 0

二、协程实现网络通信

server.py:

#! /usr/bin/python
# -*- coding:UTF-8 -*-

#服务端程序
from gevent import  monkey;monkey.patch_all()
from socket import *
import gevent

def server(server_ip,port):
    s = socket(AF_INET,SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    s.bind((server_ip,port))
    s.listen(5)
    while True:
        conn,addr = s.accept()
        gevent.spawn(talk,conn,addr)

def talk(conn,addr):
    try:
        while True:
            res = conn.revc(1024)
            print("client %s:%s msg:%s"%(addr[0],addr[1],res.decode('utf-8')))
            conn.send(res.upper())

    except Exception as e:
        print(e)

    finally:
        conn.close()



def main():
    server('127.0.0.1',8088)

    pass

if __name__ == '__main__':
    main()

client.py:

#! /usr/bin/python
# -*- coding:UTF-8 -*-

from socket import *
#客户端程序


def main():
    client = socket(AF_INET,SOCK_STREAM)
    client.connect(('127.0.0.1',8088))
    while True:
        msg = input(">> ").strip()
        if not msg:continue
        client.send(msg.encode('utf-8'))
        msg = client.recv(1024)
        print(msg.decode('utf-8'))

    pass

if __name__ == '__main__':
    main()

运行结果为:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值