The threading version handles multi-tasking:
#!/usr/bin/env python#-*-coding:utf-8-*-import threadingimport itertoolsimport timeimport sysclass Signal: go= Truedef Spin (msg,signal): write,flush=sys.stdout.write,sys.stdout.flush for char in itertools.cycle (' |/-\\ '): #会把传入的数据无限迭代下去 Status=char + ' +msg write (status) flush () write (' \x08 ' *len (status)) Time.sleep (1) if not signal.go: break Write (' * len (status) + ' \x08 ' *len (status)) def slow_function (): C12/>time.sleep (3) return 42def supervisor (): signal=signal () spinner=threading. Thread (target=spin,args= (' thinking! ', signal)) print (' Spinner object: ', spinner) Spinner.start () Result=slow_function () signal.go=false spinner.join () return resultdef main (): result= Supervisor () print (' Answer: ', result) if __name__== ' __main__ ': Main ()
Thread here Note: Be sure to block the main thread by releasing the Gil in order to create another thread, perform multi-tasking
Co-processing multi-tasking
Import Asyncioimport itertoolsimport sys@asyncio.coroutinedef Spin (msg): write,flush=sys.stdout.write, Sys.stdout.flush for Char in itertools.cycle (' |/-\\ '): status=char+ ' +msg write (status) flush () write (' \x08 ' *len (status)) #换行的 try: yield from asyncio.sleep (1) except Asyncio. Cancellederror: Break write (' hello ' + ' \ n ') @asyncio. Coroutinedef slow_function (): yield from Asyncio.sleep (3) return 42@asyncio.coroutinedef supervisor (): Spinner=asyncio.async (Spin (' thinking! ')) Print (' Spinner object: ', spinner) Result=yield from Slow_function () spinner.cancel () return Resultdef Main (): loop=asyncio.get_event_loop () Result=loop.run_until_complete (Supervisor ()) Loop.close () print (' Answer: ', result) if __name__== ' __main__ ': Main ()
The process performs multi-tasking by creating a green path, and yield from mode. At the same time, there's only one co-process here.
@asyncio. Coroutine can be added without extra, preferably with. Just to declare that this is a co-process
The above two results are as follows:
Rotation of the pointer thinking, three seconds later 42
Note the point:
About the process, the Chinese online data errors are full of errors, looking at various explanations, embarrassed, can not help laughing aloud. Explain the error, spread like wildfire hundred, alas, heartache, this is China's open source business does not come to one of the important reasons
In particular, yield from the interpretation of the basic people online is wrong
Yield from effect:
Yield from in the process of the role: to give control to the scheduler. Then we can understand how the process works.
Handling multi-tasking threads and co-process comparisons