GIL

Python has GIL (Global Interpreter Lock) which will blocks CPU — which only allow a single thread to talk to CPU at the same time in a python program.

However for I/O bounded task it is not affected. The following example proves that it still works with I/O bound

import threading
import time

# Function to simulate an I/O-bound operation
def perform_io_operation(thread_id):
    print(f"Thread {thread_id}: Started I/O operation\n")
    time.sleep(2)  # Simulate a 2-second I/O operation
    print(f"Thread {thread_id}: Completed I/O operation\n")

# Create two threads to perform I/O operations
thread1 = threading.Thread(target=perform_io_operation, args=(1,))
thread2 = threading.Thread(target=perform_io_operation, args=(2,))

# Start both threads
thread1.start()
thread2.start()

# Wait for both threads to complete
thread1.join()
thread2.join()

print("All threads have completed.")

Pasted image 20231012220012.png

A Solution is to use asyncio which implements Coroutine to handle the thread more effectively