码迷,mamicode.com
首页 > 其他好文 > 详细

十.协程

时间:2018-02-26 23:21:12      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:异步   协作式   greenlet   调度   soc   ddr   单线程   ide   encoding   

 

Greenlet

greenlet是一个用C实现的协程模块,相比与python自带的yield,它可以使你在任意函数之间随意切换,而不需把这个函数先声明为generator

from greenlet import greenlet
def test1():
    print(12)
    gr2.switch()
    print(34)
    gr2.switch()
def test2():
    print(56)
    gr1.switch()
    print(78)

gr1 = greenlet(test1) 
gr2 = greenlet(test2)
gr1.switch()

 

 

Gevent 

Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。 Greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。

import gevent

def foo():
    print(Running in foo)
    gevent.sleep(2)
    print(Running in foo2)
def bar():
    print(running bar)
    gevent.sleep(1)
    print(running bar2)
def func3():
    print("running func3 ")
    gevent.sleep(0)
    print("running func3  again ")

 

通过gevent实现单线程下的多socket并发

#server side 

import sys
import socket
import time
import gevent

from gevent import socket,monkey
monkey.patch_all()


def server(port):
    s = socket.socket()
    s.bind((0.0.0.0, port))
    s.listen(500)
    while True:
        cli, addr = s.accept()
        gevent.spawn(handle_request, cli)



def handle_request(conn):
    try:
        while True:
            data = conn.recv(1024)
            print("recv:", data)
            conn.send(data)
            if not data:
                conn.shutdown(socket.SHUT_WR)

    except Exception as  ex:
        print(ex)
    finally:
        conn.close()
if __name__ == __main__:
    server(8001)
#client side   

import socket

HOST = localhost    # The remote host
PORT = 8001           # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    msg = bytes(input(">>:"),encoding="utf8")
    s.sendall(msg)
    data = s.recv(1024)
    #print(data)

    print(Received, repr(data))
s.close()

 

十.协程

标签:异步   协作式   greenlet   调度   soc   ddr   单线程   ide   encoding   

原文地址:https://www.cnblogs.com/hiss/p/8476211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!