Junior — Middle
How do you choose conditions for switching execution between threads?
sobes.tech AI
Answer from AI
In Python, context switching between threads occurs through the operating system's thread scheduler and the GIL (Global Interpreter Lock) mechanism. Conditions for switching are usually determined by locks, I/O waits, or explicit calls such as time.sleep(), threading.Event().wait(), or when the GIL is released.
To manage switching, synchronization primitives from the threading module are used:
- Lock / RLock — block access to a resource; switching occurs when a thread waits for the lock to be released.
- Event — a thread waits for an event; switching occurs when the event is set.
- Condition — allows threads to wait for a specific condition.
Example of using Event for switching execution:
import threading
import time
event = threading.Event()
def worker():
print('Waiting for event...')
event.wait() # switch until the event is set
print('Event occurred! Continuing work.')
thread = threading.Thread(target=worker)
thread.start()
time.sleep(2)
print('Setting event')
event.set() # switch to worker thread
thread.join()
Thus, the conditions for switching are chosen based on the need for synchronization and waiting for specific events or resources.