Creating a simple Thread

A thread is the mechanism for a program to perform a task several times in parallel. Therefore, in a script, we can launch the same task on a single processor a certain number of times.

For working with threads in Python, we have two options:

  • The thread module provides primitive operations to write multithreaded programs.
  • The threading module provides a more convenient interface.

The thread module will allow us to work with multiple threads:

In this example, we create four threads, and each one prints a different message on the screen that is passed as a parameter in the thread_message (message) method.

You can find the following code in the threads_init.py file in threads subfolder:

import threadimport timenum_threads ...

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.