Multithreading or threading is the solution to running ‘several processes’ at once. Threading gives us parallel execution.

Note: it’s not truly paralel as the operating system still executes thread sequentially.

Related course:

Python Threading example

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.

import queue
import threading
import urllib.request

def getUrl(q, url):
print('getUrl('+url+') called from a thead.')

theurls = ["", "",""]

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”.

multithreading in python

A program can have any number of threads, each of which work on some data.

Download exercises