Raspberry_Pi_Education_Manual

Notes:

When accessing the web, you will not get an immediate response to your requests. When you ran the previous Python experiment you may have been lucky and had it take little time to get your weather reports. Computers can do many things very quickly and it is a shame to leave a computer waiting. This experiment shows how your computer can weave threads of instructions together so they appear to run at the same time. To avoid waiting for all the pages to respond, you can tell the computer to run all five requests for these weather reports at the same time and not wait for others to return before storing the result. The technique is called “ threading ”. Each thread runs at the same time as the others. Each weather report request is made using “urlopen”, as before, and each will stop its thread until it has a response but it will not stop the others. When each is finished it will continue. Threads can be used for anything that you want to execute at the same time but problems occur if they start changing the same bit of memory – so, be warned . Imagine writing an email on your computer and someone else also wanting to type into the same email at the same time! The experiment defines a class that can open a URL as a thread and record the data returned in a global list of results. This class creates a new thread to open a URL for each web address, and starts it. The main program waits until the number of active threads returns to the same number as before the threads were started.

Notice how it takes much less time for the five URLs to be requested when they are executed concurrently.

Experiments in Python

110

Made with FlippingBook flipbook maker