Mastering Python for Networking and Security
上QQ阅读APP看书,第一时间看更新

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 threading
class 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 threading
from ThreadWorker import ThreadWorker

def main():
# This initializes ''thread'' as an instance of our Worker Thread
thread = ThreadWorker()
# This is the code needed to run our thread
thread.start()

if __name__ == "__main__":
main()
Documentation about the threading module is available at  https://docs.python.org/3/library/threading.html.