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