Concurrent programming module greenlet ~~~ ~~~ coroutine, gevent module

A coroutine

1. coroutine:

单线程下的并发,又称微线程,纤程.协程是一种用户态的轻量级线程,即协程是由用户程序自己控制调度的.

Concurrent real core: switch and hold.

Open concurrently coroutine execution, the control program with its own CPU to switch back and forth between a plurality of tasks + hold.

Comparative thread switching operation control system, a user controls the switching of the advantages and disadvantages in the single-threaded coroutine:

2. Benefits:

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

3. Disadvantages:

协程的本质是单线程,无法利用多核.

4. coroutine features:

  1. It must be implemented concurrently in only a single thread in
  2. Modify shared data does not need to be locked
  3. Save your user program control flow stack multiple contexts

Two greenlet module

Real coroutine module is used to complete the handover greenlet

from greenlet import greenlet
import time
def eat(name):
    print(f'{name} eat 1')
    g2.switch('太白')
    time.sleep(3)
    print(f'{name} eat 2')
    g2.switch()

def play(name):
    print(f'{name} play 1')
    g1.switch()
    print(f'{name} play 2')

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

g1.switch('太白')

Three gevent module

from gevent import monkey;monkey.patch_all() 
# 打补丁 必须放在被打补丁者的前面,后面所有的阻塞全都能识别到
import gevent
import time
def eat(name):
    print(f'{name} eat 1')
    time.sleep(2)
    print(f'{name} eat 2')

def play(name):
    print(f'{name} play 1')
    time.sleep(1)
    print(f'{name} play 2')

g1 = gevent.spawn(eat,'太白')
g2 = gevent.spawn(play,'太白')
gevent.joinall([g1,g2])

Guess you like

Origin www.cnblogs.com/lav3nder/p/11802366.html