码迷,mamicode.com
首页 > 其他好文 > 详细

Gevent中的同步与异步详解

时间:2017-01-04 18:20:37      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:gevent   处理   分享   name   阻塞   res   isa   height   同步异步   

  同步,异步概念

  1.同步就是发生调用时,一定等待结果返回,整个调用才结束;

  2.异步就是发生调用后,立即返回,不等待结果返回。被调用者通过状态、通知来通知调用者,或通过回调函数处理这个调用。

  查询

  1.同步查询

技术分享

  2.异步查询

技术分享

  同步异步与阻塞,非阻塞区别

  1.阻塞/非阻塞, 它们是程序在等待消息(无所谓同步或者异步)时的状态;

  2.同步/异步,是程序获得关注消息通知的机制。

  同步异步与阻塞,非阻塞组合

  1.同步阻塞

  效率最低(日志程序)。

  2.同步非阻塞

  效率也不高(需要轮询)。

  3.异步阻塞

  一般模式线程回调。

  4.异步非阻塞

  IOCP

  实例

  import redis

  import Queue

  import time

  from threading import Thread

  def handle_callback( res ) :

  print ‘ get redis res : ‘ , res

  class SetData :

  def __init__( self , key , value , handle ) :

  self.key = key

  self.value = value

  self.handle = handle

  class RedisAsyncHandle ( Thread ) :

  queue = Queue.Queue ( maxsize = 1024 )

  r = redis.Redis ( host = ‘ localhost ‘ , port = 6379 , db = 0 )

  def send_set_cmd ( self , key , value ) :

  set_data = SetData ( key , value , handle_callback )

  self.queue.put( set_data )

  def run ( self ) :

  while True :

  while not self.queue.empty():

  item = self.queue.get()

  print ‘ get item ‘

  res = self.r.set ( item.key , item.value )

  item.handle( res )

  time.sleep( 0.1 )

  handle = RedisAsyncHandle()

  handle.start()

  handle.send_set_cmd ( ‘ name1 ‘ , ‘ allen1 ‘ )

  handle.join()

  执行结果:

技术分享

 

原文链接:http://www.maiziedu.com/wiki/frame/together/

 

Gevent中的同步与异步详解

标签:gevent   处理   分享   name   阻塞   res   isa   height   同步异步   

原文地址:http://www.cnblogs.com/space007/p/6249608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!