Python coroutine

Time:2020-9-16

 

Before the coroutine, we understand the process and thread of Python. Here, let’s talk about the coroutine

  • Instead, the subroutine switches itself
  • There is no overhead of thread switching. Compared with multithreading, the more threads there are, the more obvious the performance advantage of coprocessor
  • There is no need for multi-threaded locking mechanism, because there is only one thread, and there is no conflict of writing variables at the same time. In the coprocessor, the shared resources are not locked
  • Coprocessing implementation
 
def custumer():
    r = ''
    while True:
        N = yield R ා accept the value of send and return the value of yield
        if not n:
            return
        print('custer {}'.format(n))
        r = 'done'

def produce(c):
    c. Send (none) ා start
    n = 0
    while n < 5:
        n += 1
        print('custer {}'.format(n))
        r = c.send(n)
        print('custer return {}'.format(r))
    c.close()

c = custumer()
produce(c)

 

This article first appeared on Python black hole, and the blog Garden was updated synchronously