留坑

参考:

  1. https://en.wikipedia.org/wiki/Coroutine
  2. https://zh.wikipedia.org/wiki/协程
  3. http://www.cnblogs.com/xybaby/p/6323358.html

值得注意的点:

  1. Python对协程的支持是通过generator实现的。
  2. Python中,generator的send和throw方法使得generator很像一个协程(coroutine), 但是generator只是一个半协程(semicoroutines),python doc是这样描述的:“All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where should the execution continue after it yields; the control is always transferred to the generator’s caller.
  3. 一个线程可以多个协程,一个进程也可以单独拥有多个协程,这样python中则能使用多核CPU。(多进程+协程)
  4. greenlet是真正的协程
  5. Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。

例子1. 用协程实现生产者,消费者模型

  1. 参考:https://blog.csdn.net/pfm685757/article/details/49924099
  2. 参考:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432090171191d05dae6e129940518d1d6cf6eeaaa969000
  1. """
  2. 1. 用协程实现消费者生产者模型
  3. 2. Python对协程的支持是通过generator实现的
  4. 3. 有yield的话,就是generator
  5. 4. 整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务。
  6. """
  7. def consumer():
  8. r = ''
  9. while True:
  10. # n为send过来的值
  11. # yield类似于断点,有两个作用。
  12. # 1. 生成值
  13. # 2. 在这里断点,交出控制权。切换到另外一个协程
  14. n = yield r
  15. if not n:
  16. return
  17. print('[CONSUMER] Consuming %s...' % n)
  18. r = '200 OK'
  19. def produce(c):
  20. #start generator with None
  21. c.send(None)
  22. n = 0
  23. while n < 5:
  24. n = n + 1
  25. print('[PRODUCER] Producing %s...' % n)
  26. #启动生成器,并附带一个值,r接收yield生成的值
  27. r = c.send(n)
  28. print('[PRODUCER] Consumer return: %s' % r)
  29. c.close()
  30. c = consumer()
  31. produce(c)

例子2. 遇到IO阻塞时自动切换任务,based on gevent,greenlet,monkey

  1. from gevent import monkey; monkey.patch_all()
  2. import gevent
  3. from urllib.request import urlopen
  4. def f(url):
  5. print('GET: %s' % url)
  6. resp = urlopen(url)
  7. data = resp.read()
  8. print('%d bytes received from %s.' % (len(data), url))
  9. gevent.joinall([
  10. gevent.spawn(f, 'https://www.python.org/'),
  11. gevent.spawn(f, 'https://www.yahoo.com/'),
  12. gevent.spawn(f, 'https://www.baidu.com/'),
  13. ])

例子3. 单线程下实现多socket并发,based on gevent

server.py

  1. import sys
  2. import socket
  3. import time
  4. import gevent
  5. from gevent import socket,monkey
  6. monkey.patch_all()
  7. def server(port):
  8. s = socket.socket()
  9. s.bind(('0.0.0.0', port))
  10. s.listen(500)
  11. while True:
  12. cli, addr = s.accept()
  13. gevent.spawn(handle_request, cli)
  14. def handle_request(conn):
  15. try:
  16. while True:
  17. data = conn.recv(1024)
  18. print("recv:", data)
  19. conn.send(data + ' [server]'.encode('utf-8'))
  20. if not data:
  21. conn.shutdown(socket.SHUT_WR)
  22. except Exception as ex:
  23. print(ex)
  24. finally:
  25. conn.close()
  26. if __name__ == '__main__':
  27. server(8006)

client.py

  1. import socket
  2. import threading
  3. def sock_conn():
  4. client = socket.socket()
  5. client.connect(("localhost",8006))
  6. count = 0
  7. while True:
  8. #msg = input(">>:").strip()
  9. #if len(msg) == 0:continue
  10. #从客户端收到的数据
  11. client.send( ("hello %s" %count).encode("utf-8"))
  12. #从服务器端收到的数据
  13. data = client.recv(1024)
  14. print("[%s]recv from server:" % threading.get_ident(),data.decode()) #结果
  15. count +=1
  16. client.close()
  17. for i in range(100):
  18. t = threading.Thread(target=sock_conn)
  19. t.start()

操作系统OS,Python - 协程(Coroutine)的更多相关文章

  1. Python 协程 (Coroutine)

    协程 (Coroutine) 什么是协程 协程(微线程)是比线程更轻量化的存在,像一个进程可以拥有多个线程一样,一个线程也可以拥有多个协程 最重要的是,协程不是被操作系统内核所管理,而完全是由程序所控 ...

  2. Python并发编程协程(Coroutine)之Gevent

    Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate routine的缩写,直接翻译 ...

  3. Python之协程(coroutine)

    Python之协程(coroutine) 标签(空格分隔): Python进阶 coroutine和generator的区别 generator是数据的产生者.即它pull data 通过 itera ...

  4. python协程(yield、asyncio标准库、gevent第三方)、异步的实现

    引言 同步:不同程序单元为了完成某个任务,在执行过程中需靠某种通信方式以协调一致,称这些程序单元是同步执行的. 例如购物系统中更新商品库存,需要用"行锁"作为通信信号,让不同的更新 ...

  5. 5分钟完全掌握Python协程

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 1. 协程相关的概念 1.1 进程和线程 进程(Process)是应用程序启动的实例,拥有代码.数据 ...

  6. (zt)Lua的多任务机制——协程(coroutine)

    原帖:http://blog.csdn.net/soloist/article/details/329381 并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上 ...

  7. 协程coroutine

    协程(coroutine)顾名思义就是“协作的例程”(co-operative routines).跟具有操作系统概念的线程不一样,协程是在用户空间利用程序语言的语法语义就能实现逻辑上类似多任务的编程 ...

  8. Lua的多任务机制——协程(coroutine)

    并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上有这么两种多任务技术,一种是抢占式多任务(preemptive multitasking),它让操作系统来决定 ...

  9. 再议Python协程——从yield到asyncio

    协程,英文名Coroutine.前面介绍Python的多线程,以及用多线程实现并发(参见这篇文章[浅析Python多线程]),今天介绍的协程也是常用的并发手段.本篇主要内容包含:协程的基本概念.协程库 ...

随机推荐

  1. PostGreSql - 提取jsonb数据

    本文主要介绍如何在PostGreSql中提取出jsonb类型字段中的某个key的值 参考:https://www.cnblogs.com/mywebnumber/p/5551092.html 一.简单 ...

  2. layui-table 样式

    <!DOCTYPE html> <html> <head> <style> #lay-table { background-color: #fff; c ...

  3. const和defin区别

    (1)类型的安全性检查:const常量有数据类型,而define定义宏常量没有数据类型.则编译器可以对前者进行类型安全检查,而对后者只进行字符替换,没有类型安全检查(字符替换时可能会产生意料不到的错误 ...

  4. h5 调起app 如果没安装就跳转下载

    <!doctype html> <html> <head> <title></title> <meta charset="u ...

  5. C语言中二维数组如何申请动态分配内存

    C语言中二维数组如何申请动态分配内存: 使用malloc函数,先分配第一维的大小,然后再循环分配每一维的大小 #include <stdio.h> #include <malloc. ...

  6. Django 无法同步数据库model相应字段问题

    前言:今天也是充满bug的一天,脸上笑嘻嘻....(继续,讲文明,懂礼貌) 1,问题描述,models中的字段设置的是浮点型,但是输出的结果总是int()类型 models average_score ...

  7. Django objects.all()、objects.get()与objects.filter()之间的区别介绍

    前言 本文主要介绍的是关于Django objects.all().objects.get()与objects.filter()直接区别的相关内容,文中介绍的非常详细,需要的朋友们下面来一起看看详细的 ...

  8. ACL与OSPF综合实验

    OSPF与ACL 综合实验   拓扑图如下: 分析: 配置基本配置: R1: R2: R3: 2.配置OSPF: R1: R2: R3: IT: 设置IT的ip 并划分到ospf2区域 3.配置ACL ...

  9. robot用例执行常用命令

    执行命令 执行一个用例 robot -t “testcase_name“ data_test.robot 按用例文件执行 robot data_test.robot或者 robot --suite “ ...

  10. 用svn客户端checkout时报错RA layer request failed

    用svn客户端checkout时报错: RA layer request failedsvn: Unable to connect to a repository at URL 'https://30 ...