Python併發編程:協程-gevent模塊

一 gevent模塊python

Gevent是一個第三方庫,能夠輕鬆經過gevent實現併發同步或異步編程。在gevent中用到的主要模式是Greenlet,它是以C擴展模塊形式接入Python的輕量級協程。Greenlet 所有運行在主程序操做系統進程的內部,但它們被協做式地調度。編程

# 用法
g1=gevent.spawn(func,1,2,3,x=4,y=5)建立一個協程對象g1,spawn括號內第一個參數是函數名,如eat,後面能夠有多個參數,能夠是位置實參或關鍵字實參,都是傳給函數eat的

g2 = gevent.spawn(func2)

g1.join()    # 等待g1結束

g2.join()    # 等待g2結束

# 或者上述兩步合做一步:gevent.joinall([g1,g2])

g1.value    # 拿到func1的返回值

  遇到IO阻塞時會自動切換任務併發

import gevent

def eat(name):
    print('%s eat 1' % name)
    gevent.sleep(2)
    print('%s eat 2' % name)

def play(name):
    print('%s play 1' % name)
    gevent.sleep(1)
    print('%s play 2' % name)


g1 = gevent.spawn(eat, 'mike')
g2 = gevent.spawn(play, 'mike')
g1.join()
g2.join()

print('主')

 

上例gevent.sleep(2)模擬的是gevent能夠識別的io阻塞異步

而time.sleep(2)或其它的阻塞,gevent是不能直接識別的須要用下面一行代碼,打補丁,就能夠識別了socket

from gevent import monkey;monkey.patch_all()必須放到被打補丁者的前面,如time,socket模塊以前異步編程

或者咱們乾脆記憶成:要用gevent,須要將from gevent import monkey;monkey.patch_all()放到文件的開頭函數

from gevent import monkey;monkey.patch_all()
import gevent
import time

def eat(name):
    print('%s eat 1' % name)
    time.sleep(2)
    print('%s eat 2' % name)

def play(name):
    print('%s play 1' % name)
    time.sleep(1)
    print('%s play 2' % name)


g1 = gevent.spawn(eat, 'mike')
g2 = gevent.spawn(play, 'mike')
g1.join()
g2.join()

print('主')

  咱們能夠用threading.current_thread().getName()來查看每一個g1和g2,查看的結果爲DummyThread-n,即假線程spa

 二 練習操作系統

# 服務端

from gevent import monkey;monkey.patch_all()
from socket import *
import gevent

# 若是不想用monkey.patch_all()打補丁,能夠用gevent自帶的socket
# from gevent import socket
# s = socket.socket()

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.recv(1024)
            print('client %s:%s msg: %s' % (addr[0], addr[1], res))
            conn.send(res.upper())
    except Exception as e:
        print(e)

    finally:
        conn.close()


if __name__ == '__main__':
    server('127.0.0.1', 8080)

  

客戶端線程

from threading import Thread
from socket import *
import threading


def client(server_ip, port):
    c = socket(AF_INET, SOCK_STREAM)    # 套接字對象必定要加到函數內,即局部名稱空間內,放在函數外則被全部線程共享,則你們公用一個套接字對象,那麼客戶端端口永遠同樣了
    c.connect((server_ip, port))

    count = 0
    while True:
        c.send(('%s say hello %s' % (threading.current_thread().getName(), count)).encode('utf-8'))
        msg = c.recv(1024)
        print(msg.decode('utf-8'))
        count += 1


if __name__ == '__main__':
    for i in range(500):
        t = Thread(target=client, args=('127.0.0.1', 8080))
        t.start()
相關文章
相關標籤/搜索