Techwetrust
Techwetrust is a programming blog maintained by Alin Alexandru, a young Python developer. He addresses topics like Python tutorials, Docker tutorials and other tech-related articles.

How to use threads in Python 3 [the easy way]

In this tutorial, you’ll learn to use threading in Python 3 using the default library concurrent.futures.

What are the advantages of using concurrent.futures?

  • less code to write
  • asynchronous threads
  • a high-level interface for using threads

Basic example

from concurrent import futures

with futures.ThreadPoolExecutor() as executor:
    # submit a task to our pool of threads
    future = executor.submit(pow, 3,2)

future.result() # will print 9

Advanced example

We can use threads to process multiple tasks asynchronously. A common example is with multiple requests.

import requests
from concurrent import futures

urls = [
    'https://httpbin.org/get?page=1',
    'https://httpbin.org/get?page=2',
    'https://httpbin.org/get?page=3',
    'https://httpbin.org/get?page=4',
    'https://httpbin.org/get?page=5',
]

def make_request(url):
    response = requests.get(url)
    print(url)

with futures.ThreadPoolExecutor() as executor:
    executor.map(make_request, urls)

# This will output the URLs in a random order
# In my case of execution the output was:
# https://httpbin.org/get?page=4
# https://httpbin.org/get?page=1
# https://httpbin.org/get?page=5
# https://httpbin.org/get?page=3
# https://httpbin.org/get?page=2

The map method accepts a function name and an iterable.

function: It is a function to which map passes each element of given iterable.
iterable: Lists, tuples, dictionaries, and sets which will be mapped.

[1] Python 3 concurrent.futures

Alin Alexandru

@skykery

Hello! My name is Banuta Alexandru Alin and I am working as a full-time programmer. I have experience in data mining, data science, and data parsing/crawling. I like to travel when I have some days off. May my knowledge help you and protect your way!

Leave a Reply