Junior — Middle
Can thread switching be controlled in Python?
sobes.tech AI
Answer from AI
In Python, you can control thread switching using the threading module. Although the CPython interpreter uses the GIL (Global Interpreter Lock), which limits the concurrent execution of bytecode in multiple threads, you can manage threads by creating, starting, and synchronizing them.
Example of creating and starting threads:
import threading
import time
def worker(name):
print(f"Thread {name} started")
time.sleep(2)
print(f"Thread {name} finished")
thread1 = threading.Thread(target=worker, args=("A",))
thread2 = threading.Thread(target=worker, args=("B",))
thread1.start()
thread2.start()
thread1.join() # Wait for thread1 to finish
thread2.join() # Wait for thread2 to finish
print("All threads are finished")
You can use methods like start(), join(), and also synchronize threads using locks (Lock), events (Event), and other primitives from the threading module.
For lower-level control, you can use the thread module (called _thread in Python 3), but it is less convenient and safe.
If you need parallel processing without GIL restrictions, consider using the multiprocessing module.