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

Recommended Today

The real problem of Alibaba IOS algorithm can’t hang up this time

More and more IOS developers continue to enter the peak of job hopping in 2020 Three main trends of interview in 2020: IOS bottom layer, algorithm, data structure and audio and video development Occupied the main battlefield. Data structure and algorithm interview, especially figure, has become the main reason for the failure of most first-line […]