💻

Introduction to Multi-threading in Python

Jul 20, 2024

Lecture Notes: Introduction to Multi-threading in Python

What is Multi-threading?

  • Used to perform multiple tasks concurrently (multitasking).
  • Good for IO-bound tasks (e.g., reading files, fetching data from an API).

Example Analogy

  • Similar to multitasking in daily life: studying, listening to music, and eating at the same time.

Using Multi-threading in Python

Importing the Module

  • import threading

Creating Threads

  • Use the threading.Thread constructor.
  • Pass in a target function.

Example: Performing Chores

  1. Functions to Define Chores:

    • Walk the dog: Prints "You finish walking the dog" after sleeping for 8 seconds.
    • Take out trash: Prints "You take out the trash" after sleeping for 2 seconds.
    • Get mail: Prints "You get the mail" after sleeping for 4 seconds.
  2. Calling Functions Sequentially:

    • Calls functions one by one on the main thread:
      • Walk the dog -> Take out trash -> Get mail.
    • Takes 14 seconds total (8+2+4).

Implementing Multi-threading

  1. Creating Thread Objects for Each Chore:

    • chore1 = threading.Thread(target=walk_dog)
    • chore2 = threading.Thread(target=take_out_trash)
    • chore3 = threading.Thread(target=get_mail)
  2. Starting Threads:

    • chore1.start(), chore2.start(), chore3.start()
  3. Output Order:

    • Chores finish in the order of completion time due to concurrent execution:
      • Take out trash -> Get mail -> Walk the dog.
    • Total time reduced to 8 seconds (time of the longest task).

Ensuring Completion of All Threads

  • Use join method to wait for all threads to complete before printing final message.
    • Example: chore1.join() chore2.join() chore3.join() print("All chores are complete")

Passing Arguments to Threads

  • Use args keyword in Thread constructor.
  • Example with single argument: threading.Thread(target=walk_dog, args=("Scooby",))
  • Example with multiple arguments: threading.Thread(target=walk_dog, args=("Scooby", "Doo"))

Summary

  • Multi-threading allows concurrent task execution.
  • Beneficial for IO-bound tasks.
  • Use threading.Thread with target and args (if needed).
  • Use start to begin threads and join to ensure completion.