In this tutorial, we will explore the basics of threading in Python. We will break down simple examples using the threading module and progressively dive into more complex scenarios.
Overview
Threading allows concurrent execution of multiple tasks (or threads) within a program. Python’s built-in threading module makes it easy to handle threads and boost performance for I/O-bound tasks.
1. Simple Example: Running Multiple Threads
The example below shows how to create and run two threads concurrently:
import threading
import time
# Define a function to run in threads
def print_numbers():
for i in range(5):
print(f"Number: {i}")
time.sleep(1) # Simulate a time-consuming task
# Create two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)
# Start the threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print("Both threads have finished execution.")
- We define a function print_numbers() that prints numbers from 0 to 4 with a 1-second delay between prints.
- We create two threads using threading.Thread and pass the target function.
- The threads are started with start() and waited upon using join().
2. Example 2: Passing Arguments to Threads
Now, let’s modify the code to pass arguments to the thread functions:
import threading
import time
# Define a function with arguments
def print_numbers(name, count):
for i in range(count):
print(f"{name} - Number: {i}")
time.sleep(1)
# Create threads with different arguments
thread1 = threading.Thread(target=print_numbers, args=("Thread1", 3))
thread2 = threading.Thread(target=print_numbers, args=("Thread2", 5))
# Start the threads
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print("All threads have completed.")
Explanation:
- The print_numbers function now takes two arguments: name and count.
- We pass these arguments using the args parameter when creating the threads.
- Each thread behaves independently, printing its own sequence of numbers.
3. Example: Inheriting from threading.Thread
Another approach is to create a custom class by inheriting from threading.Thread. Below is a simple example:
import threading
import time
from typing import Dict, List
class CustomThread(threading.Thread):
thread_store: Dict[str, List[threading.Thread]] = {}
def __init__(self, name: str, count: int):
super().__init__()
self.name = name
self.count = count
def run(self):
"""The entry point for the thread."""
for i in range(self.count):
print(f"{self.name} - Number: {i}")
time.sleep(1)
# Create and start threads
thread1 = CustomThread("Thread1", 3)
thread2 = CustomThread("Thread2", 5)
thread1.start()
thread2.start()
# Wait for both threads to finish
thread1.join()
thread2.join()
print("Custom threads have completed.")
Explanation:
- Class Definition: The CustomThread class inherits from threading.Thread.
- Shared Resource: thread_store is a class-level dictionary for managing threads if needed in more complex cases.
- Initialization: The __init__ method calls super().__init__() to ensure proper initialization of the thread.
- Overriding run(): The run() method defines the code that will execute in the thread.
- Creating and Starting Threads: We instantiate the custom threads and start them with start().
- Joining Threads: join() ensures that the main program waits for both threads to complete.
'Pytorch Beginner' 카테고리의 다른 글
PyTorch_002_Implementing a Graph Convolutional Network (GCN) Layer (0) | 2025.02.17 |
---|---|
PyTorch_001_Building a Fully Connected Neural Network (1) | 2024.12.23 |