Python co-step face Test (i)

Source: Internet
Author: User
Topic

Using the concept of a coprocessor, enter a value of a,b,c,d four integers, printing (a+b) * (C+D) for the following purposes. Suppose the a+b process is a 1-second IO operation. The author's answer

"" "
using the concept of a coprocessor, enter a,b,c,d four integers, print (a+b) * (c+d) value" ""
import Asyncio, OS from
threading Import Current_thread


# defines the covariant
async def sum (A, B) that is responsible for computing two digits,
    print (""%s-%s "coroutine start to do:%s +%s"% (OS.GETP ID (), Current_thread (). GetName (), A, b)
    await asyncio.sleep (1) # simulates a 1-second IO operation, automatically switches the co-
    r = Int (a) + int (b)
    Print (""%s-%s "Coroutine End for:%s +%s, the result is  %s"% (Os.getpid (), Current_thread (). GetName (), A, B, R))
    R Eturn R


# defines the main function
def main (A, B, C, D):
    loop = Asyncio.get_event_loop ()
    task = Asyncio.gather (
        Sum (A, b),
        sum (c, D)
    )
    loop.run_until_complete (Task)
    r1, r2 = Task.result ()
    r = R1 * R2
    Print (""%s-%s "%s *%s =%s"% (Os.getpid (), Current_thread (). GetName (), R1, R2, R))
    Loop.close ()


if __name__ = = ' __main__ ':
    Main (1, 2, 3, 4)

Printing process and results:

"23729-mainthread" coroutine start to Do:1 + 2
"23729-mainthread" coroutine start to Do:3 + 4
"23729-mainthread" Co Routine end For:1 + 2, result was  3
"23729-mainthread" Coroutine end For:3 + 4, result is  7
"23729-maint Hread "3 * 7 = 21

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.