Skip to content
Python

Multithreading

Implement multithreading using the threading module.

By EZ4Code Team
threadingmultithreading

Code

import threading
from concurrent.futures import ThreadPoolExecutor

def task(n):
    return n * n

# Using thread pool
with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(task, range(10)))
    print(results)

# Manually create thread
threads = []
for i in range(5):
    t = threading.Thread(target=task, args=(i,))
    threads.append(t)
    t.start()
for t in threads:
    t.join()

Explanation

ThreadPoolExecutor is the recommended way to use threads, automatically managing the thread pool.

More Python Snippets