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
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.