Threads and Python
- Thread-based parallelism is the standard way of writing parallel programs
- The python interpreter is not fully thread-safe
- In order to support multithreaded Python programs, a global lock called the Global Interpreter Lock (GIL) is used.
- Only one thread can execute the python code at the same time.
- Python automatically switches to next thread after a short period of time.
- If multiple threads attempt to access the same data object, it may end up in an inconsistent state.
from threading import Thread
from time import sleep
# To create a thread in Python, you'll want to make your class work as a thread.
# For this, you should subclass your call from the Thread class
self.message = "Hello parallel code!"
# this method prints only the message
# the run method prints ten times the message
print("Thread firing up")
x = 0
while x < 10:
x += 1
# start the main process
hello_py = CookBook()
- While the main program has ended, the threads continue to run every 2 seconds.
- This depicts what threads are: a subtask doing something in parent process.
- A key point is to make sure no thread keeps running in background.