The existence of the Gil Lock makes it possible for Python to achieve multi-threaded parallelism through multicore, and if you want Python to take advantage of multicore, it can only be done by opening multiple processes. So Python is suitable for computationally intensive tasks.
Resource preemption: threads, processes
Co-operation: Cooperative----> Non-preemptive program, Keywords: yield generator, the main solution is also IO operations, but can not take advantage of multi-core (no multi-process case)
Multi-process + coprocessor: resolves process concurrency
Relive the yield generator:
deff ():Print("OK") s=yield6Print(s)Print("Ok2") yieldGen=f ()#Print (gen)#Next (gen)Ret=gen.__next__()Print(RET)#Next (gen)Gen.send (5)
The advantages of the process: 1) No switching consumption (involving the IO operation will automatically switch); 2) The concept of no lock is essentially a thread
Concurrency can be achieved by using the co-thread + multithreading.
Time-driven programming idea: a programming paradigm.
The following are the implementation of the co-process:
#From greenlet import Greenlet##def test1 ():#print (All)#Gr2.switch ()#print ($)#def test2 ():#print (+)#Gr1.switch ()#Print (%)#Gr1.switch ()##Gr1 = Greenlet (test1)#GR2 = Greenlet (test2)#Gr2.switch ()
ImportgeventImportRequests,timestart=time.time ()deff (URL):Print('GET:%s'%URL) Resp=requests.get (URL) data=Resp.textPrint('%d bytes received from%s.'%(len (data), URL)) #f ('https://www.python.org/') #f ('https://www.yahoo.com/') #f ('https://www.baidu.com/') #f ('https://www.sina.com.cn/') #f ("http://www.xiaohuar.com/hua/")Gevent.joinall ([gevent.spawn (F, ' https://www.python.org/'),gevent.spawn (F, ' https://www.yahoo.com/'),gevent.spawn (F, ' https://www.baidu.com/'),gevent.spawn (F, ' https://www.sina.com.cn/'),gevent.spawn (F, ' http://www.xiaohuar.com/hua/'), ])Print("Cost Time :", Time.time ()-start)
python-Multithreading + co-process