Python coroutine test

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.