Python threads, processes, Ctrip, I/O synchronization, asynchronous

Source: Internet
Author: User

Only I can read-python thread, process, Ctrip, I/O synchronization, asynchronous

give me a chestnut :

I want to get three URLs, first with a normal for loop

ImportRequests fromMultiprocessingImportProcess fromThreadingImportThreadImportRequestsImport Time#-----Normal traversal of the serial synchronization-----defget_page (URL): page=requests.get (URL)Print(URL) Start=time.time () URLs= ['http://jandan.net/','https://www.python.org','http://www.gamersky.com/'] forIinchurls:get_page (i) End=time.time ()Print(End-start)
# this is normal.

This time I'm going to use the threading module to get him a little faster.

defget_page (URL): page=requests.get (URL) Start=time.time () List= []#List of Thread objectsURLs = ['http://jandan.net/','http://www.xiaohuar.com/','http://www.gamersky.com/'] forIinchUrls:ok= Thread (target=get_page,args= (i,))#target is the function name, and args is the parameter passed to the functionlist.append (OK)#get_page (i) forIinchList:i.start ()#Start a thread forIinchList:i.join ()#The main thread waits for the child thread to finish after executionEnd =time.time ()Print(End-start)
# opened three threads to run
# If the thread uses the Join () function (the main thread code will stop in join), the main process waits for the child thread to finish executing
# If the child thread (Ok.setdeamon (True)becomes a daemon thread, the main thread will not wait for the child thread to finish executing, and when the main thread ends, it will be forced to terminate, regardless of whether the child thread finishes execution!

Python threads, processes, Ctrip, I/O synchronization, asynchronous

Related Article

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.