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

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 thread
import time

num_threads = 4

def thread_message(message):
global num_threads
num_threads -= 1
print('Message from thread %s\n' %message)

while num_threads > 0:
print "I am the %s thread" %num_threads
thread.start_new_thread(thread_message,("I am the %s thread" %num_threads,))
time.sleep(0.1)

We can see more information about the start_new_thread() method if we invoke the help(thread) command: