Python multithreading

Multithreading is similar to executing multiple different programs at the same time. Multithreading has the following advantages:

  • Using threads can put tasks in long-running programs in the background for processing.
  • The user interface can be more attractive, such as when the user clicks a button to trigger the processing of certain events, a progress bar can pop up to show the progress of the process
  • Programs may run faster
  • Threads are useful in some waiting tasks such as user input, file reading and writing, and network sending and receiving data. In this case we can release some precious resources such as memory usage and so on.

The thread is still different from the process during execution. Each individual process has an entry for program execution, a sequence of sequential executions, and an exit for the program. However, threads cannot be executed independently, and must be executed by the application in multiple threads depending on the presence of the application.

Each thread has its own set of CPU registers, called the context of the thread, which reflects the state of the CPU register that the thread last ran for.

The instruction pointer and the stack pointer register are the two most important registers in the thread context. Threads are always run in the context of the process. These addresses are used to mark the memory in the process address space of the owning thread. .

  • Threads can be preempted (interrupted).
  • When other threads are running, the thread can be put on hold (also known as sleep) -- this is the thread's backoff.

Start learning Python threads

Python uses threads in two ways: by function or by wrapping a thread object with a class.

Function: Call the start_new_thread() function in the thread module to generate a new thread. The syntax is as follows:

thread.start_new_thread ( function,< /span> args[, kwargs] )

Parameter description:

  • function - the thread function.
  • args - the argument passed to the thread function, which must be a tuple type.
  • kwargs - optional parameters.

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass

Execute the above program output as follows:

Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

The end of a thread generally depends on the natural end of the thread function; you can also call thread.exit() in the thread function, which throws the SystemExit exception to achieve the purpose of exiting the thread.

Threading Module

Python provides threading support through two standard libraries, thread and threading. Thread provides low-level, raw threads and a simple lock.

Other methods provided by the threading module:

  • threading.currentThread(): Returns the current thread variable.
  • threading.enumerate(): Returns a list containing the running threads. Running After the thread is started, before the end, it does not include the thread before and after the start.
  • threading.activeCount(): Returns the number of threads that are running, with the same result as len(threading.enumerate()).

In addition to using methods, the thread module also provides a Thread class to handle threads. The Thread class provides the following methods:

  • run(): A method used to represent thread activity.
  • start(): Start thread activity.

  • join([time]): Wait until the thread is aborted. This blocks the calling thread until the thread's join() method is called to abort - exit normally or throw an unhandled exception - or an optional timeout occurs.
  • isAlive(): Returns whether the thread is active.
  • getName(): Returns the thread name.
  • setName(): Set the thread name.

Create a thread using the Threading module

Create a thread using the Threading module, inherit directly from threading.Thread, and then override the __init__ method and the run method:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time exitFlag = 0 class myThread (threading.Thread): #Inheriting parent class threading.Thread def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID = name self.counter = counter def run(self): #Write the code to be executed to the run function. The thread will run the run function directly after creation print "Starting " + print_time(, self.counter, 5) print "Exiting " + def print_time(threadName, delay, counter): while counter: if exitFlag: (threading.Thread).exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create a new thread thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Open thread thread1.start() thread2.start() print "Exiting Main Thread"

javacodegeeks is optimized for learning.© javacodegeeks
All Right Reserved and you agree to have read and accepted our term and condition.