Sobes.tech
Junior — Middle

How is the context switch performed when working with multithreaded programming?

sobes.tech AI

Answer from AI

Context switching in multithreaded programming is the process of saving the current thread's state and loading another's, allowing the processor to switch between them.

In Python, when using threads (the threading module), context switching occurs automatically by the operating system scheduler and the Python interpreter. Due to GIL (Global Interpreter Lock), only one thread executes at a time in CPython, but switching between threads happens quickly.

Example:

import threading
import time

def worker(name):
    for i in range(3):
        print(f"{name} is working {i}")
        time.sleep(1)

thread1 = threading.Thread(target=worker, args=("Thread 1",))
thread2 = threading.Thread(target=worker, args=("Thread 2",))

thread1.start()
thread2.start()

thread1.join()
thread2.join()

Here, context switching occurs during calls to time.sleep() and system interrupts, allowing threads to switch.

In lower-level languages, context switching involves saving CPU registers, stack, and other data, but in Python, this is hidden.