python-Multithreading + co-process

Source: Internet
Author: User

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

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.