Python

Making code faster

Importing files

Multiprocessing

About some Modules

Use the built-in threading module.

import threading

Quick links:

Creating and Running Threads

The core class is threading.Thread.

Basic Example

import threading
import time

def worker_function(name):
    print(f"Worker thread {name} starting...")
    time.sleep(2) # Simulate doing some I/O work
    print(f"Worker thread {name} finishing.")

# Create two threads
t1 = threading.Thread(target=worker_function, args=("Alpha",))
t2 = threading.Thread(target=worker_function, args=("Beta",))

# Start the threads
t1.start()
t2.start()

# Wait for both threads to complete
t1.join()
t2.join()

print("All threads finished.")

Sharing Data & The GIL

Threads share memory, which makes data sharing easier but requires careful synchronization (using Locks, Semaphores, etc.) to prevent race conditions.