Multithreading in Python

Python has an API that allow us to write applications with multiple threads. To get started with multithreading, we are going to create a new thread inside a python class and call it ThreadWorker.py. This class extends from threading.Thread and contains the code to manage one thread:

import threadingclass ThreadWorker(threading.Thread):    # Our workers constructor    def __init__(self):        super(ThreadWorker, self).__init__()    def run(self):        for i in range(10):           print(i)

Now that we have our thread worker class, we can start to work on our main class. Create a new python file, call it main.py, and put the following code in:

import threadingfrom ThreadWorker import ThreadWorkerdef main(): # This initializes ''thread'' as an ...

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.