Threads are typically used when:
- A program needs to execute multiple tasks concurrently.
- Some tasks involve waiting, such as I/O operations (e-mail sending, network calls, file operations, etc.).
- You want to keep the application responsive while running background work.
- You need lightweight parallelism without creating separate processes.
Threads are ideal for:
- Sending emails
- Handling multiple client requests
- Downloading/uploading files
- Handling background tasks in GUI applications
A thread generally consists of:
- A function to execute
- Optional arguments
- A thread controller to run the task either synchronously or asynchronously
In real Python code, this might look like:
from threading import Thread
thread = Thread(target=function_name, args=(arg1, arg2))
thread.start()But the examples below are simplified pseudo code to demonstrate the idea.
def send_email(sender, receiver, message):
email.send(sender, receiver, message)
email_thread = Thread(send_email, ['sender_email', 'receiver_email', 'text'])
email_thread.run()Explanation
The send_email() function performs a time-consuming operation.
A thread is created to handle the email sending process without blocking the main program.
def create_file(name):
my_file = File(name)
my_file.create()
for i from 1 to 1000000:
my_file.append(i)
for file_name from 1 to 100:
Thread(create_file, [file_name]).async().run()We create 100 threads, each generating and writing into a separate file.
.async().run() means the files are created in parallel (non-blocking).
This simulates heavy I/O operations that benefit from multi-threading.