python coroutine测试

本文介绍了一种实现异步任务的方法,并通过一个简单的例子展示了如何使用回调和线程来模拟异步操作。此外,还提供了一个协程的实现方案,通过事件对象实现了任务的挂起与恢复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:实现一个类似于asyn await的用法,来方便的编写callback相关函数

 

from __future__ import print_function
import time
import threading

def asyn_task(callback):
def SleepTask():
time.sleep(1)
callback("world")
# t = threading.Timer(1.0, lambda :callback("world"))
t = threading.Thread(target=SleepTask)
t.start() # after 30 seconds, "hello, world" will be printed


def main():
asyn_task(lambda s:print(s))
print ("hello")

def main2():
class myCoroutine:
def __init__(self):
self.evt = threading.Event()
self.co=self.myCOroutine()
self.co.next()
def myCOroutine(self):
while 1:
self.evt.clear()
line = (yield)
# print ('yield:' + line)
self.line = line
self.evt.set()

def await(self):
self.evt.wait()
return self.line

def send(self, *args):
self.co.send(*args)

g = myCoroutine()
asyn_task(lambda s:g.send(s))
print ("hello")
s = g.await()
print (s)


main2()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值