回调函数是实现异步操作的常用手法

 

1、callback版本的示例,其中framework调用logic,在完成某些操作或者接收到信号后,用callback返回异步结果

#!/usr/bin/env python2.7

def framework(logic,callback):
        s=logic()
        print "[FX] logic:",s
        print "[FX] do something..."

        for i in xrange(1000000):
                a=i+1
        callback("async:"+s)

def logic():
        s="mylogic"
        return s

def callback(s):
        print s


framework(logic,callback)

 2、使用yield改进的blocking style版本:

#!/usr/bin/env python2.7
#-*- coding:utf8 -*-

def framework(logic):
        try:
                it = logic()
                s = next(it)

                print "[FX] logic:",s
                print "[FX] do something"

                f=open("test.txt",'w')
                for i in xrange(1000000000):
                        f.write(str(i)+'\n')
                f.close()

                it.send("async:" + s)
        except StopIteration:
                pass

def logic():
        s = "mylogic"
        r = yield s

        print r

framework(logic)

 

相关文章:

  • 2021-05-30
  • 2021-08-02
  • 2021-10-10
  • 2022-02-26
  • 2021-05-19
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-28
  • 2022-12-23
  • 2021-06-07
  • 2021-11-13
  • 2021-11-08
  • 2022-01-14
  • 2021-10-01
相关资源
相似解决方案