1、差异说明
实现多任务时,线程切换从系统层面远不止保存和恢复CPU上下文这么简单。操作系统为了程序运行的高效性,每个线程都有自己缓存Cache等数据,操作系统还会帮你做这些数据的恢复工作。所以线程的切换非常耗性能。
协程的切换只是单纯的操作CPU的上下文,一秒钟切换个上百万次系统都可以。
2、实例
import time def work1(): while True: print("----work1---") yield time.sleep(0.5) def work2(): while True: print("----work2---") yield time.sleep(0.5) def main(): w1 = work1() w2 = work2() while True: next(w1) next(w2) if __name__ == "__main__": main() ----work1--- ----work2--- ----work1--- ----work2--- ----work1--- ----work2--- ----work1--- ----work2--- ----work1--- ----work2--- ----work1--- ----work2--- ...省略...
以上就是python协程和线程的差异,希望对大家有所帮助。更多Python学习指路: