python 协程并发

# 协程并发
import gevent
from gevent import monkey
monkey.patch_all()
from socket import *
from time import ctime
def server(port):
    s=socket()
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    s.bind(('',port))
    s.listen(3)
    while True:
        c,addr=s.accept()
        print('世界如此简单',addr)
        # handler(c)
        gevent.spawn(handler,c)#协程
def handler(c):
    while True:
        data=c.recv(1024)
        if not data:
            break
        c.send(ctime().encode())
    c.close()
s.close()


if __name__=="__main__":
    server(9999)
import gevent


def f1():
    for i in range(5):
        print 'run func: f1, index: %s ' % i
        gevent.sleep(0)


def f2():
    for i in range(5):
        print 'run func: f2, index: %s ' % i
        gevent.sleep(0)


t1 = gevent.spawn(f1)
t2 = gevent.spawn(f2)
gevent.joinall([t1, t2])

你可能感兴趣的:(python基础,python)