• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python进阶九——并发编程之协程

python 搞java代码 3年前 (2022-05-21) 23次浏览 已收录 0个评论

1.协程介绍

协程:是单线程下的并发,又称微线程,纤程。英文名Coroutine。一句话说明什么是线程:协程是一种用户态的轻量级线程,即协程是由用户程序自己控制调度的。、

  需要强调的是:

#<span style="color: #800080">1</span><span style="color: #000000">. python的线程属于内核级别的,即由操作系统控制调度(如单线程遇到io或执行时间过长就会被迫交出cpu执行权限,<a href="https://www.gaodaima.com/tag/%e5%88%87%e6%8d%a2" title="查看更多关于切换的文章" target="_blank">切换</a>其他线程运行)
#</span><span style="color: #800080">2</span>. 单线程内开启协程,一旦遇到io,就会从应用程序级别(而非操作系统)控制切换,以此来提升效率(非io操作的切换与效率无关)

www#gaodaima.com来源gao*daima.com搞@代#码网搞代码

对比操作系统控制线程的切换,用户在单线程内控制协程的切换

  优点如下:

#<span style="color: #800080">1</span><span style="color: #000000">. 协程的切换开销更小,属于程序级别的切换,操作系统完全感知不到,因而更加轻量级
#</span><span style="color: #800080">2</span>. 单线程内就可以实现并发的效果,最大限度地利用cpu

      缺点如下:

#<span style="color: #800080">1</span>. 协程的本质是单线程下,无法利用多核,可以是一个程序开启多个进程,每个进程内开启多个线程,每个线程内开启协程

总结协程特点:

  1. 必须在只有一个单线程里实现并发
  2. 修改共享数据不需加锁
  3. 用户程序里自己保存多个控制流的上下文栈

2.Greenlet

如果在单个线程内有20个任务,要想实现在多个任务之间切换,使用yield生成器的方式过于麻烦(需要先得到初始化一次的生成器,然后再调用send。。。非常麻烦),而使用greenlet模块可以非常简单地实现这20个任务直接的切换

<span style="color: #000000">#安装
pip3 install greenlet</span>
<span style="color: #000000">  #真正的协程模块就是使用greenlet完成的切换

</span><span style="color: #0000ff">from</span><span style="color: #000000"> greenlet import greenlet

def eat(name):
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s eat 1</span><span style="color: #800000">"</span> %name)  #<span style="color: #800080">2</span><span style="color: #000000">
    g2.</span><span style="color: #0000ff">switch</span>(<span style="color: #800000">"</span><span style="color: #800000">yanhui</span><span style="color: #800000">"</span>)   #<span style="color: #800080">3</span><span style="color: #000000">
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s eat 2</span><span style="color: #800000">"</span> %name) #<span style="color: #800080">6</span><span style="color: #000000">
    g2.</span><span style="color: #0000ff">switch</span>() #<span style="color: #800080">7</span><span style="color: #000000">
def play(name):
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s play 1</span><span style="color: #800000">"</span> %name) #<span style="color: #800080">4</span><span style="color: #000000">
    g1.</span><span style="color: #0000ff">switch</span>()      #<span style="color: #800080">5</span><span style="color: #000000">
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s play 2</span><span style="color: #800000">"</span> %name) #<span style="color: #800080">8</span><span style="color: #000000">

g1</span>=<span style="color: #000000">greenlet(eat)
g2</span>=<span style="color: #000000">greenlet(play)

g1.</span><span style="color: #0000ff">switch</span>(<span style="color: #800000">"</span><span style="color: #800000">yanhui</span><span style="color: #800000">"</span>)#可以在第一次switch时传入参数,以后都不需要  <span style="color: #800080">1</span>

单纯的切换(在没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度

<span style="color: #000000">#顺序执行
import time
def f1():
    res</span>=<span style="color: #800080">1</span>
    <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">100000000</span><span style="color: #000000">):
        res</span>+=<span style="color: #000000">i

def f2():
    res</span>=<span style="color: #800080">1</span>
    <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">100000000</span><span style="color: #000000">):
        res</span>*=<span style="color: #000000">i

start</span>=<span style="color: #000000">time.time()
f1()
f2()
stop</span>=<span style="color: #000000">time.time()
print(</span><span style="color: #800000">"</span><span style="color: #800000">run time is %s</span><span style="color: #800000">"</span> %(stop-start)) #<span style="color: #800080">10.985628366470337</span><span style="color: #000000">

#切换
</span><span style="color: #0000ff">from</span><span style="color: #000000"> greenlet import greenlet
import time
def f1():
    res</span>=<span style="color: #800080">1</span>
    <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">100000000</span><span style="color: #000000">):
        res</span>+=<span style="color: #000000">i
        g2.</span><span style="color: #0000ff">switch</span><span style="color: #000000">()

def f2():
    res</span>=<span style="color: #800080">1</span>
    <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">100000000</span><span style="color: #000000">):
        res</span>*=<span style="color: #000000">i
        g1.</span><span style="color: #0000ff">switch</span><span style="color: #000000">()

start</span>=<span style="color: #000000">time.time()
g1</span>=<span style="color: #000000">greenlet(f1)
g2</span>=<span style="color: #000000">greenlet(f2)
g1.</span><span style="color: #0000ff">switch</span><span style="color: #000000">()
stop</span>=<span style="color: #000000">time.time()
print(</span><span style="color: #800000">"</span><span style="color: #800000">run time is %s</span><span style="color: #800000">"</span> %(stop-start)) # <span style="color: #800080">52.763017892837524</span>

效率对比

     greenlet只是提供了一种比generator更加便捷的切换方式,当切到一个任务执行时如果遇到io,那就原地阻塞,仍然是没有解决遇到IO自动切换来提升效率的问题,协程虽然没有规避固有的I/O时间,但是我们使用这个时间来做别的事情了,一般在工作中我们都是进程+线程+协程的方式来实现并发,以达到最好的并发效果,如果是4核的cpu,一般起5个进程,每个进程中20个线程(5倍cpu数量),每个线程可以起500个协程,大规模爬取页面的时候,等待网络延迟的时间的时候,我们就可以用协程去实现并发。 并发数量 = 5 * 20 * 500 = 50000个并发,这是一般一个4cpu的机器最大的并发数。nginx在负载均衡的时候最大承载量就是5w个

  单线程里的这20个任务的代码通常会既有计算操作又有阻塞操作,我们完全可以在执行任务1时遇到阻塞,就利用阻塞的时间去执行任务2。。。。如此,才能提高效率,这就用到了Gevent模块。

3.Gevent介绍

<span style="color: #000000">#安装
pip3 install gevent</span>

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

     

<span style="color: #000000">#用法
g1</span>=gevent.spawn(func,<span style="color: #800080">1</span>,<span style="color: #800080">2</span>,<span style="color: #800080">3</span>,x=<span style="color: #800080">4</span>,y=<span style="color: #800080">5</span><span style="color: #000000">)创建一个协程对象g1,spawn括号内第一个参数是函数名,如eat,后面可以有多个参数,可以是位置实参或关键字实参,都是传给函数eat的,spawn是异步提交任务

g2</span>=<span style="color: #000000">gevent.spawn(func2)

g1.join() #等待g1结束

g2.join() #等待g2结束  有人测试的时候会发现,不写第二个join也能执行g2,是的,协程帮你切换执行了,但是你会发现,如果g2里面的任务执行的时间长,但是不写join的话,就不会执行完等到g2剩下的任务了


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

g1.value#拿到func1的返回值</span>

遇到IO阻塞时会自动切换任务

<span style="color: #000000">import gevent
def eat(name):
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s eat 1</span><span style="color: #800000">"</span> %<span style="color: #000000">name)
    gevent.sleep(</span><span style="color: #800080">2</span><span style="color: #000000">)
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s eat 2</span><span style="color: #800000">"</span> %<span style="color: #000000">name)

def play(name):
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s play 1</span><span style="color: #800000">"</span> %<span style="color: #000000">name)
    gevent.sleep(</span><span style="color: #800080">1</span><span style="color: #000000">)
    print(</span><span style="color: #800000">"</span><span style="color: #800000">%s play 2</span><span style="color: #800000">"</span> %<span style="color: #000000">name)


g1</span>=gevent.spawn(eat,<span style="color: #800000">"</span><span style="color: #800000">egon</span><span style="color: #800000">"</span><span style="color: #000000">)
g2</span>=gevent.spawn(play,name=<span style="color: #800000">"</span><span style="color: #800000">egon</span><span style="color: #800000">"</span><span style="color: #000000">)
g1.join()
g2.join()
#或者gevent.joinall([g1,g2])
print(</span><span style="color: #800000">"</span><span style="color: #800000">主</span><span style="color: #800000">"</span><span style="color: #000000">)

遇到I</span>/O切换

遇到I/O切换

上例gevent.sleep(2)模拟的是gevent可以识别的io阻塞,

  而time.sleep(2)或其他的阻塞,gevent是不能直接识别的需要用下面一行代码,打补丁,就可以识别了

  from gevent import monkey;monkey.patch_all()必须放到被打补丁者的前面,如time,socket模块之前

  或者我们干脆记忆成:要用gevent,需要将from gevent import monkey;monkey.patch_all()放到文件的开头

<span style="color: #0000ff">from</span><span style="color: #000000"> gevent import monkey;monkey.patch_all() #必须写在最上面,这句话后面的所有阻塞全部能够识别了

import gevent  #直接导入即可
import time
def eat():
    #print()  
    print(</span><span style="color: #800000">"</span><span style="color: #800000">eat food 1</span><span style="color: #800000">"</span><span style="color: #000000">)
    time.sleep(</span><span style="color: #800080">2</span><span style="color: #000000">)  #加上mokey就能够识别到time模块的sleep了
    print(</span><span style="color: #800000">"</span><span style="color: #800000">eat food 2</span><span style="color: #800000">"</span><span style="color: #000000">)

def play():
    print(</span><span style="color: #800000">"</span><span style="color: #800000">play 1</span><span style="color: #800000">"</span><span style="color: #000000">)
    time.sleep(</span><span style="color: #800080">1</span>)  #来回切换,直到一个I/<span style="color: #000000">O的时间结束,这里都是我们个gevent做得,不再是控制不了的操作系统了。
    print(</span><span style="color: #800000">"</span><span style="color: #800000">play 2</span><span style="color: #800000">"</span><span style="color: #000000">)

g1</span>=<span style="color: #000000">gevent.spawn(eat)
g2</span>=<span style="color: #000000">gevent.spawn(play_phone)
gevent.joinall([g1,g2])
print(</span><span style="color: #800000">"</span><span style="color: #800000">主</span><span style="color: #800000">"</span>)

       可以用threading.current_thread().getName()来查看每个g1和g2,查看的结果为DummyThread-n,即假线程,虚拟线程,其实都在一个线程里面

  进程线程的任务切换是由操作系统自行切换的,你自己不能控制

  协程是通过自己的程序(代码)来进行切换的,自己能够控制,只有遇到协程模块能够识别的IO操作的时候,程序才会进行任务切换,实现并发效果,如果所有程序都没有IO操作,那么就基本属于串行执行了

4.Gevent之同步与异步  

<span style="color: #0000ff">from</span><span style="color: #000000"> gevent import spawn,joinall,monkey;monkey.patch_all()

import time
def task(pid):
    </span><span style="color: #800000">"""
</span>    Some non-<span style="color: #000000">deterministic task
    </span><span style="color: #800000">"""
</span>    time.sleep(<span style="color: #800080">0.5</span><span style="color: #000000">)
    print(</span><span style="color: #800000">"</span><span style="color: #800000">Task %s done</span><span style="color: #800000">"</span> %<span style="color: #000000"> pid)


def synchronous():
    </span><span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">10</span><span style="color: #000000">):
        task(i)

def asynchronous():
    g_l</span>=[spawn(task,i) <span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">10</span><span style="color: #000000">)]
    joinall(g_l)

</span><span style="color: #0000ff">if</span> __name__ == <span style="color: #800000">"</span><span style="color: #800000">__main__</span><span style="color: #800000">"</span><span style="color: #000000">:
    print(</span><span style="color: #800000">"</span><span style="color: #800000">Synchronous:</span><span style="color: #800000">"</span><span style="color: #000000">)
    synchronous()

    print(</span><span style="color: #800000">"</span><span style="color: #800000">Asynchronous:</span><span style="color: #800000">"</span><span style="color: #000000">)
    asynchronous()
#上面程序的重要部分是将task函数封装到Greenlet内部线程的gevent.spawn。 初始化的greenlet列表存放在数组threads中,此数组被传给gevent.joinall 函数,后者阻塞当前流程,并执行所有给定的greenlet。执行流程只会在 所有greenlet执行完后才会继续向下走。

协程:同步异步对比</span>

同步异步对比

5.Gevent之应用举例一

<span style="color: #0000ff">from</span><span style="color: #000000"> gevent import monkey;monkey.patch_all()
import gevent
import requests
import time

def get_page(url):
    print(</span><span style="color: #800000">"</span><span style="color: #800000">GET: %s</span><span style="color: #800000">"</span> %<span style="color: #000000">url)
    response</span>=requests.<span style="color: #0000ff">get</span><span style="color: #000000">(url)
    </span><span style="color: #0000ff">if</span> response.status_code == <span style="color: #800080">200</span><span style="color: #000000">:
        print(</span><span style="color: #800000">"</span><span style="color: #800000">%d bytes received from %s</span><span style="color: #800000">"</span> %<span style="color: #000000">(len(response.text),url))


start_time</span>=<span style="color: #000000">time.time()
gevent.joinall([
    gevent.spawn(get_page,</span><span style="color: #800000">"</span><span style="color: #800000">https://www.python.org/</span><span style="color: #800000">"</span><span style="color: #000000">),
    gevent.spawn(get_page,</span><span style="color: #800000">"</span><span style="color: #800000">https://www.yahoo.com/</span><span style="color: #800000">"</span><span style="color: #000000">),
    gevent.spawn(get_page,</span><span style="color: #800000">"</span><span style="color: #800000">https://github.com/</span><span style="color: #800000">"</span><span style="color: #000000">),
])
stop_time</span>=<span style="color: #000000">time.time()
print(</span><span style="color: #800000">"</span><span style="color: #800000">run time is %s</span><span style="color: #800000">"</span> %(stop_time-<span style="color: #000000">start_time))

协程应用:爬虫</span>

协程应用:爬虫

将上面的程序最后加上一段串行的代码看看效率:如果你的程序不需要太高的效率,那就不用什么并发啊协程啊之类的东西

print(<span style="color: #800000">"</span><span style="color: #800000">--------------------------------</span><span style="color: #800000">"</span><span style="color: #000000">)
s </span>=<span style="color: #000000"> time.time()
requests.</span><span style="color: #0000ff">get</span>(<span style="color: #800000">"</span><span style="color: #800000">https://www.python.org/</span><span style="color: #800000">"</span><span style="color: #000000">)
requests.</span><span style="color: #0000ff">get</span>(<span style="color: #800000">"</span><span style="color: #800000">https://www.yahoo.com/</span><span style="color: #800000">"</span><span style="color: #000000">)
requests.</span><span style="color: #0000ff">get</span>(<span style="color: #800000">"</span><span style="color: #800000">https://github.com/</span><span style="color: #800000">"</span><span style="color: #000000">)
t </span>=<span style="color: #000000"> time.time()
print(</span><span style="color: #800000">"</span><span style="color: #800000">串行时间>></span><span style="color: #800000">"</span>,t-s)

View Code

6.Gevent之应用举例二

         通过gevent实现单线程下的socket并发(from gevent import monkey;monkey.patch_all()一定要放到导入socket模块之前,否则gevent无法识别socket的阻塞)

一个网络请求里面经过多个时间延迟time.

<span style="color: #0000ff">from</span><span style="color: #000000"> gevent import monkey;monkey.patch_all()
</span><span style="color: #0000ff">from</span> socket import *<span style="color: #000000">
import gevent

#如果不想用money.patch_all()打补丁,可以用gevent自带的socket
# </span><span style="color: #0000ff">from</span><span style="color: #000000"> gevent import socket
# s</span>=<span style="color: #000000">socket.socket()

def server(server_ip,port):
    s</span>=<span style="color: #000000">socket(AF_INET,SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,</span><span style="color: #800080">1</span><span style="color: #000000">)
    s.bind((server_ip,port))
    s.listen(</span><span style="color: #800080">5</span><span style="color: #000000">)
    </span><span style="color: #0000ff">while</span><span style="color: #000000"> True:
        conn,addr</span>=<span style="color: #000000">s.accept()
        gevent.spawn(talk,conn,addr)

def talk(conn,addr):
    </span><span style="color: #0000ff">try</span><span style="color: #000000">:
        </span><span style="color: #0000ff">while</span><span style="color: #000000"> True:
            res</span>=conn.recv(<span style="color: #800080">1024</span><span style="color: #000000">)
            print(</span><span style="color: #800000">"</span><span style="color: #800000">client %s:%s msg: %s</span><span style="color: #800000">"</span> %(addr[<span style="color: #800080">0</span>],addr[<span style="color: #800080">1</span><span style="color: #000000">],res))
            conn.send(res.upper())
    except Exception </span><span style="color: #0000ff">as</span><span style="color: #000000"> e:
        print(e)
    </span><span style="color: #0000ff">finally</span><span style="color: #000000">:
        conn.close()

</span><span style="color: #0000ff">if</span> __name__ == <span style="color: #800000">"</span><span style="color: #800000">__main__</span><span style="color: #800000">"</span><span style="color: #000000">:
    server(</span><span style="color: #800000">"</span><span style="color: #800000">127.0.0.1</span><span style="color: #800000">"</span>,<span style="color: #800080">8080</span>)

服务端

<span style="color: #0000ff">from</span> socket import *<span style="color: #000000">

client</span>=<span style="color: #000000">socket(AF_INET,SOCK_STREAM)
client.connect((</span><span style="color: #800000">"</span><span style="color: #800000">127.0.0.1</span><span style="color: #800000">"</span>,<span style="color: #800080">8080</span><span style="color: #000000">))


</span><span style="color: #0000ff">while</span><span style="color: #000000"> True:
    msg</span>=input(<span style="color: #800000">"</span><span style="color: #800000">>>: </span><span style="color: #800000">"</span><span style="color: #000000">).strip()
    </span><span style="color: #0000ff">if</span> not msg:<span style="color: #0000ff">continue</span><span style="color: #000000">

    client.send(msg.encode(</span><span style="color: #800000">"</span><span style="color: #800000">utf-8</span><span style="color: #800000">"</span><span style="color: #000000">))
    msg</span>=client.recv(<span style="color: #800080">1024</span>)

客户端

<span style="color: #0000ff">from</span><span style="color: #000000"> threading import Thread
</span><span style="color: #0000ff">from</span> socket import *<span style="color: #000000">
import threading

def client(server_ip,port):
    c</span>=<span style="color: #000000">socket(AF_INET,SOCK_STREAM) #套接字对象一定要加到函数内,即局部名称空间内,放在函数外则被所有线程共享,则大家公用一个套接字对象,那么客户端端口永远一样了
    c.connect((server_ip,port))

    count</span>=<span style="color: #800080">0</span>
    <span style="color: #0000ff">while</span><span style="color: #000000"> True:
        c.send((</span><span style="color: #800000">"</span><span style="color: #800000">%s say hello %s</span><span style="color: #800000">"</span> %(threading.current_thread().getName(),count)).encode(<span style="color: #800000">"</span><span style="color: #800000">utf-8</span><span style="color: #800000">"</span><span style="color: #000000">))
        msg</span>=c.recv(<span style="color: #800080">1024</span><span style="color: #000000">)
        print(msg.decode(</span><span style="color: #800000">"</span><span style="color: #800000">utf-8</span><span style="color: #800000">"</span><span style="color: #000000">))
        count</span>+=<span style="color: #800080">1</span>
<span style="color: #0000ff">if</span> __name__ == <span style="color: #800000">"</span><span style="color: #800000">__main__</span><span style="color: #800000">"</span><span style="color: #000000">:
    </span><span style="color: #0000ff">for</span> i <span style="color: #0000ff">in</span> range(<span style="color: #800080">500</span><span style="color: #000000">):
        t</span>=Thread(target=client,args=(<span style="color: #800000">"</span><span style="color: #800000">127.0.0.1</span><span style="color: #800000">"</span>,<span style="color: #800080">8080</span><span style="color: #000000">))
        t.start()</span>

多线程并发多个客户端,去请求上面的服务端是没问题的

 


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python进阶九——并发编程之协程

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址