Purpose: to implement a usage similar to Asyn await, to facilitate the writing of callback related functions
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 the seconds, "hello, world" would 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 ()
Python coroutine test