Skip to content

Latest commit

 

History

History
70 lines (50 loc) · 1.89 KB

File metadata and controls

70 lines (50 loc) · 1.89 KB

Thread Basics in Python

When Are Threads Used?

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

Structure of a Thread

A thread generally consists of:

  1. A function to execute
  2. Optional arguments
  3. 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.

Pseudo Code Examples

1. Sending an Email (Pseudo Code)

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.

2. Creating Many Files (Pseudo Code)

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()

Explanation

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.