python3.5 provides the async and await syntax for Asyncio, using both of these to simplify the implementation of the co-process.
1 ImportAsyncio2 ImportRandom3 4 5AsyncdefSMART_FIB (n):6index =07A =08b = 19 whileIndex <N:TenSleep_secs = random.uniform (0, 0.2) One await Asyncio.sleep (sleep_secs) A Print('Smart one Think {} secs to get {}'. Format (sleep_secs, b)) -A, B = B, A +b -Index + = 1 the - -AsyncdefSTUPID_FIB (n): -index =0 +A =0 -b = 1 + whileIndex <N: ASleep_secs = random.uniform (0, 0.4) at await Asyncio.sleep (sleep_secs) - Print('Stupid one Think {} secs to get {}'. Format (sleep_secs, b)) -A, B = B, A +b -Index + = 1 - - in - if __name__=='__main__': toloop =Asyncio.get_event_loop () +tasks = [ -Asyncio.ensure_future (SMART_FIB (10)), theAsyncio.ensure_future (STUPID_FIB (10)), * ] $ Loop.run_until_complete (asyncio.wait (tasks))Panax Notoginseng Print('All Fib finished.') -Loop.close ()
Python co-process