Multithreading or threading is the solution to running ‘several processes’ at once. Threading gives us parallel execution.
Related course: Complete Python Bootcamp: Go from zero to hero in Python
we use the modules threading and queue to start several threads. A queue is created by calling Queue(). Then we have an array of urls as parameter for thread construction.
Threads are created in the for loop using the call threading.Thread(). Then they have to be started by calling thead.start(). Every thread calls the method getUrl.
def getUrl(q, url):
print('getUrl('+url+') called from a thead.')
theurls = ["http://google.com", "http://google.de","http://google.ca"]
threadQueue = queue.Queue()
for u in theurls:
t = threading.Thread(target=getUrl, args = (threadQueue,u))
t.daemon = True
output = threadQueue.get()
Graphically this is what happens. Your program (the main thread) starts several new threads which execute a task “in parallel”.
A program can have any number of threads, each of which work on some data.