1. Co-process-Intro
The topic of this section is to implement concurrency based on a single thread, i.e. only one main thread, which is obviously the only one of the CPUs available, we need to look back at the nature of Concurrency: Switch + save state CPU is running a task, In either case, the task is cut off to perform other tasks (the switchover is controlled by the operating system), in which case it is blocked, and the other is that the task is taking too long to calculate or has a higher priority program replacing it
Three states of the process:
Run, block, ready
ps:在介绍进程理论时,提及进程的三种执行状态,而线程才是执行单位,所以也可以将理解为线程的三种状态
Import Time#Serial ExecutiondefConsumer (res):Passdefproducer (): Res= [] forIinchRange (100000): Res.append (i)returnResstart=time.time () Res=producer () consumer (res) Stop=time.time ()Print(Stop-start)#execute based on yield concurrencyImport Timedefconsumer (): whiletrue:x=yielddefproducer (): G=consumer () Next (g) forIinchRange (100000): G.send (i) Start=time.time ()#based on the yield save state, two tasks are switched back and forth directly, that is, the effect of concurrency#PS: If you add a print to each task, it is obvious that the print of two tasks is the one I once, which executes concurrently.producer () Stop=time.time ()Print(Stop-start)
View Code
Two: The first case of the switch. In the case of a task encountered Io, cut to the task two to execute, so that the task can be used to block the time to complete the task two calculation, the increase in efficiency is this. yield does not meet IO switching
2, the introduction of the association Process
协程的本质就是在单线程下,由用户自己控制一个任务遇到io阻塞了就切换另外一个任务去执行,以此来提升效率。
为了实现它,我们需要找寻一种可以同时满足以下条件的解决方案:
1. You can control the switch between multiple tasks, save the state of the task before switching, so that you can resume execution based on the paused position when you rerun. 2. As a 1 supplement: You can detect IO operations and switch between IO operations
2.1. Definition of the co-process
Co-process: is a single-threaded concurrency, also known as micro-threading, fiber. English name Coroutine. One sentence describes what a thread is: The process is a lightweight thread of user-state, that is, the process is scheduled by the user program itself. ,
Attention:
1. Python threads are at the kernel level, that is, scheduled by the operating system control (such as single-threaded encounter IO or long execution time will be forced to hand over the CPU execution permissions, switch other threads to run)2. Single-wire range opening process, once IO is encountered, The switch is controlled from the application level (not the operating system) to increase efficiency (!!!) Non-IO operation switching is not efficiency-independent)
2.2, the characteristics of the co-process
Intrinsically single-threaded serial execution so no lock required
13 Concurrent Programming-(co-process)-The basic concept of the association