協程

1.協程介紹

協程:
1.是單線程下的併發
2.是用戶代碼自己控制的,遇到I/O就進行程序切換,即本來運行func1,遇到I/O,就去執行func2
(但是yeild,greenlet都無法實現遇到I/O進行程序切換,只有gevent可以實現)
3.修改共享數據不需要加鎖
4.用戶程序中保存多個控制流的上下文
"線程與協程對比"
線程:Python中的線程屬於內核級別的,由操作系統控制調度
一個線程遇到I/O或執行時間過長就會被迫交出CPU,切換執行另一個線程
協程:單線程內的協程,一旦遇到I/O,就會從用戶代碼級別(不是由操作系統控制)控制切換,以此來提升效率
"非I/O操作的切換與效率無關"
"對比操作系統控制線程的切換《==》單線程內的協程切換"
協程切換的優點:
1.協程的切換開銷更小,屬於程序級別的切換,操作系統感知不到,因而更加輕量級
2.單線程內可以實現併發的效果,更大限度的利用CPU
協程切換的缺點:
1.協程的本質是在單線程下,無法利用多核,可以是一個程序開啓多個進程,每個進程內開啓多個線程,每個線程內開啓多個協程
2.協程指的是單個線程,因而一旦協程阻塞,就會阻塞整個線程

1.1yeild實現協程

對於操作系統的多線程和多進程,操作系統能做到CPU在運行一個任務,會有兩種情況CPU去執行其他任務
1.正在運行的任務發生I/O阻塞
2.正在運行的任務計算時間過長或有一個優先級更高的程序替代了它。

對於情況一,任務遇到I/O,切換到任務二去執行,這樣可以利用任務一的阻塞時間文成任務二的計算,可以提升效率
對於情況二,如果任務是純計算的,這種切換反而會降低效率
yeild實現協程有兩個缺點:
1.演示任務一運行一段,就自動切換到任務二。
    這種單純的切換,反而會降低運行效率
2.演示遇到I/O,yeild是不能進行切換的,會阻塞在那裏,等待程序的處理

1.1.1yeild單純的切換,反而會降低運行效率

實際操作中,根據操作系統的不同,配置的不同,現象會有差異
"串行運行"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#串行執行
import time
def consumer(res):
    '''任務1:接收數據,處理數據'''
    pass

def producer():
    '''任務2:生產數據'''
    res=[]
    for i in range(10000000):
        res.append(i)
    return res

start=time.time()
#串行執行
res=producer()
consumer(res) #寫成consumer(producer())會降低執行效率
stop=time.time()
print(stop-start) #0.967444896697998

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
0.967444896697998

Process finished with exit code 0
"基於yield保存狀態,實現兩個任務直接來回切換,即併發的效果"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#基於yield併發執行
import time
def consumer():
    '''任務1:接收數據,處理數據'''
    while True:
        x=yield
        #print("消費%s"%x)

def producer():
    '''任務2:生產數據'''
    g=consumer()
    next(g)
    for i in range(10000000):
        #print("生產%s"%i)
        g.send(i)

start=time.time()
#
#PS:如果每個任務中都加上打印,那麼明顯地看到兩個任務的打印是你一次我一次,即併發執行的.
producer()

stop=time.time()
print(stop-start) #0.9723668098449707

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
0.9723668098449707

Process finished with exit code 0

1.1.2yeild不能實現遇到I/O切換

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import time
def consumer():
    '''任務1:接收數據,處理數據'''
    while True:
        x=yield

def producer():
    '''任務2:生產數據'''
    g=consumer()
    next(g)
    for i in range(10000000):
        g.send(i)
        # producer遇到io就會阻塞住,並不會切到該線程內的其他任務去執行
        time.sleep(2)

start=time.time()
producer()

stop=time.time()
print(stop-start)

1.2greenlet模塊實現協程

greenlet模塊實現協程,同樣不能做到遇到I/O進行任務切換
greenlet只是提供了一種比generator更加便捷的切換方式

1.2.1greenlet模塊演示

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#安裝:pip3 install greenlet
from greenlet import greenlet

def eat(name):
    print('%s eat 1' %name)
    # 可以在第一次switch時傳入參數,以後都不需要
    g2.switch('vita')
    print('%s eat 2' %name)
    g2.switch()
def play(name):
    print('%s play 1' %name)
    g1.switch()
    print('%s play 2' %name)

g1=greenlet(eat)
g2=greenlet(play)

g1.switch('vita')#可以在第一次switch時傳入參數,以後都不需要

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
vita eat 1
vita play 1
vita eat 2
vita play 2

Process finished with exit code 0

1.2.2greenlet單純的切換,反而耗費時間

"順序執行"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#順序執行
import time
def f1():
    res=1
    for i in range(100000000):
        res+=i

def f2():
    res=1
    for i in range(100000000):
        res*=i

start=time.time()
f1()
f2()
stop=time.time()
print('run time is %s' %(stop-start)) #8.914215803146362
"greenlet切換"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#切換
from greenlet import greenlet
import time
def f1():
    res=1
    for i in range(100000000):
        res+=i
        g2.switch()

def f2():
    res=1
    for i in range(100000000):
        res*=i
        g1.switch()

start=time.time()
g1=greenlet(f1)
g2=greenlet(f2)
g1.switch()
stop=time.time()
print('run time is %s' %(stop-start)) # 53.22377419471741

1.2.3greenlet遇到I/O不會進行任務切換

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#切換
from greenlet import greenlet
import time
def f1():
    res=1
    for i in range(100000000):
        res+=i
        g2.switch()

def f2():
    res=1
    for i in range(100000000):
        res*=i
        # 遇到sleep()就會停留等在這裏,不會去執行別的任務
        time.sleep(2)
        g1.switch()

start=time.time()
g1=greenlet(f1)
g2=greenlet(f2)
g1.switch()
stop=time.time()
print('run time is %s' %(stop-start)) # 53.22377419471741
上面已經演示了yeild和greenlet模塊的多線程模式,都不能做到遇到I/O進行任務的切換,下面的gevent可以做到,讓我們來看奇蹟吧!

1.3gevent實現協程

1.3.1gevent模塊介紹

"安裝"
pip3 install gevent
"用法"
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的返回值

1.3.2gevent是異步提交任務的

"由於是異步提交任務的,所以執行完spawn後,就繼續主線程,主線程運行完了,就退出了
所以連函數都沒執行"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
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,'egon')
g2=gevent.spawn(play,name='egon')
# 這裏沒有join
#或者gevent.joinall([g1,g2])
print('主')

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
主

Process finished with exit code 0

1.3.2遇到I/O阻塞會自動切換任務

"需要join(),主線程等待,纔會運行函數"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
import gevent
def eat(name):
    print('%s eat 1' %name)
        # 遇到sleep,切換到play函數
    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,'egon')
g2=gevent.spawn(play,name='egon')
g1.join()
g2.join()
#或者gevent.joinall([g1,g2])
print('主')

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
egon eat 1
egon play 1
egon play 2
egon eat 2
主

Process finished with exit code 0
上面的gevent.sleep(2)模擬的是gevent可以識別的io阻塞
而time.sleep()或其他的阻塞,gevent要想識別,需要將from gevent import monkey;monkey.patch_all()放到文件的開頭
可以使用threading.current_thread().getName()來查看線程名
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from gevent import monkey;monkey.patch_all()
from threading import current_thread
import gevent
import time
def eat():
    print('%seat food 1'% current_thread().getName())
    time.sleep(2)
    print('%seat food 2'% current_thread().getName())

def play():
    print('%splay 1'% current_thread().getName())
    time.sleep(1)
    print('%splay 2'% current_thread().getName())

g1=gevent.spawn(eat)
g2=gevent.spawn(play)
g1.join()
g2.join()
#或者gevent.joinall([g1,g2])
print('主')

D:\software2\Python3\install\python.exe E:/PythonProject/new-python/python-test/BasicGrammer/test.py
DummyThread-1eat food 1
DummyThread-2play 1
DummyThread-2play 2
DummyThread-1eat food 2
主

Process finished with exit code 0

1.3.3gevent實現socket併發

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

#如果不想用money.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()
        # 這裏沒有join,是因爲spawn()之後,進入下一循環,主線程沒有結束
        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)

協程

"client"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
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()

協程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章