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.

important

Even though GIL guarantee that 1 thread can only execute at 1 time. There is a default context switch sys.getswitchinterval() of 0.05 seconds. This means. After 0.05 seconds, GIL will release and can be occupied by another thread to execute for another sys.getswitchinterval() (0.05) seconds.

This is similar to Context switch in CPU. Which makes sure that even in a GIL environment, GIL only locked a maximum of sys.getswitchinterval() time.
We can also change this value by using sys.setswitchinterval(seconds)

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