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
class CookBook(Thread):
def __init__(self):
Thread.__init__(self)
self.message = "Hello parallel code!"
# this method prints only the message
def print_message(self):
print(self.message)
# the run method prints ten times the message
def run(self):
print("Thread firing up")
x = 0
while x < 10:
self.print_message()
sleep(2)
x += 1
print("Thread Ended\n")
# start the main process
print("Process started")
hello_py = CookBook()
hello_py.start()
print("Process Ended")
- 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.
Leave A Comment