In this Python In multithreading tutorial , You'll see different ways to create threads , And learn to realize the synchronization of thread safe operation . Each part of this article contains an example and sample code , To explain the concept step by step .
By the way , Multithreading is the core concept of software programming supported by almost all high-level programming languages . therefore , The first thing you should know is : What is threading and what multithreading means in Computer Science .
In software programming , Thread is the smallest execution unit with independent instruction set . It's part of the process , And share the runnable resources of the program ( Such as memory ) Run in the same context . A thread has a starting point 、 An execution sequence and a result . It has an instruction pointer , It is used to save the current state of threads and control the next execution order .
The ability of a process to execute multiple threads in parallel is called multithreading . Ideally , Multithreading can significantly improve the performance of any program . and Python The multithreading mechanism is very user-friendly , You can learn quickly .
up to now , You have read about the theoretical concept of threads . If you are not familiar with it Python, We recommend that you read our 30 Fast Python Coding techniques , They can also help you write Python Multithreaded code . Many of our readers have used these techniques , And can improve their coding skills .
Python Two modules are provided to implement threading in the program .
Be careful : For your reference ,Python 2.x There used to be < thread> modular . But it's in Python 3.x Abandoned in Pay equal attention to Name it < _thread> Module for backward compatibility .
The main difference between the two modules is that the module <_ Threads > Implement the thread as a function . On the other hand ,< threading > Module provides an object-oriented method to enable thread creation .
If you decide to use... In your program < thread > modular , Then use the following method to generate threads .
# grammar thread.start_new_thread ( function, args[, kwargs] ) Copy code
This method is very effective and direct for creating threads . You can use it in Linux and Windows Middle run program .
This method starts a new thread and returns its identifier . It specifies the call using the passed parameter list as “ function ” Function of parameter . When < function > return , The thread will silently exit .
here ,args Is a parameter tuple ; Call with empty tuple < function > Without any parameters . Optional < kwargs > Parameter specifies the dictionary of keyword parameters .
** If < function > Terminated due to an unhandled exception , The stack trace is printed , Then the thread exits ( It does not affect other threads , They will continue to run ). Use the following code to learn more about threads .
#Python Multithreading example . #1. Use recursion to calculate factorials . #2. Using threads to call factorial functions . from _thread import start_new_thread from time import sleep threadId = 1 # Thread counter waiting = 2 #2 Seconds waiting time def factorial(n): global threadId rc = 0 if n < 1: # base case print("{}: {}".format('\nThread', threadId )) threadId += 1 rc = 1 else: returnNumber = n * factorial( n - 1 ) # recursive call print("{} != {}".format(str(n), str(returnNumber))) rc = returnNumber return rc start_new_thread(factorial, (5, )) start_new_thread(factorial, (4, )) print("Waiting for threads to return...") sleep(waiting) Copy code
You can be here Python Run the above code in the terminal , You can also use any online Python terminal . After executing this procedure , It will produce the following output .
Program output
# Python Multithreading : Program output - Wait for the thread to return ... Thread: 1 1 != 1 2 != 2 3 != 6 4 != 24 5 != 120 Thread: 2 1 != 1 2 != 2 3 != 6 4 != 24 Copy code
Abreast of the times < threading > The module is better than the legacy discussed in the previous section < thread > Module provides rich features and better thread support .< threading > The module is Python A good example of multithreading .
< threading > The module combines < thread > All methods of module , And exposed some additional methods
In addition to the above methods ,< threading > The module also provides < Thread > class , You can try to implement threads . It is Python Multithreaded object-oriented variants .
< Thread > Class publishes the following methods .
Class method
Method statement
run():
It is the entry point function of any thread .
start():
start() Method in run Method is called to trigger a thread .
join([time]):
join() Method enables the program to wait for the thread to terminate .
isAlive():
isAlive() Method to validate the active thread .
getName():
getName() Method to retrieve the name of the thread .
setName():
setName() Method to update the name of the thread .
You can use the following steps < threading > Module to implement a new thread .
Once a new... Is defined < Thread> Subclass , You must instantiate it to start a new thread . then , call < start()> Method to start it . It will eventually call < run()> Method to execute business logic .
#Python The multithreaded sample prints the current date . #1. Use threading.Thread Class defined subclass . #2. Instantiate subclasses and trigger threads . import threading import datetime class myThread (threading.Thread): def __init__(self, name, counter): threading.Thread.__init__(self) self.threadID = counter self.name = name self.counter = counter def run(self): print("\nStarting " + self.name) print_date(self.name, self.counter) print("Exiting " + self.name) def print_date(threadName, counter): datefields = [] today = datetime.date.today() datefields.append(today) print("{}[{}]: {}".format( threadName, counter, datefields[0] )) # Create a new thread thread1 = myThread("Thread", 1) thread2 = myThread("Thread", 2) # Start a new thread thread1.start() thread2.start() thread1.join() thread2.join() print("\nExiting the Program!!!") Copy code
Program output
Starting Thread Thread[1]: 2021-07-22 Exiting Thread Starting Thread Thread[2]: 2021-07-22 Exiting Thread Exiting the Program!!! Copy code
< threading > The module has the built-in function of locking , Allows you to synchronize threads . Locking is required to control access to shared resources , To prevent data loss or corruption .
You can call Lock() Method to apply the lock , It returns a new lock object . then , You can call the... Of the lock object obtain ( Blocking ) Method to force threads to run synchronously .
Optional Blocking Parameter specifies whether the thread is waiting to acquire the lock .
Lock object's release() Method is used to release the lock when it is no longer needed .
For reference only ,Python Built in data structure ( For example, a list of 、 Dictionaries ) It's thread safe , Because it has the side effect of the atomic bytecode used to manipulate them . stay Python Other data structures or basic types implemented in ( Such as integers and floating point numbers ) Without this protection . To prevent simultaneous access to an object , We used a Lock object .
#Python Multithreading example to demonstrate locking . #1. Use threading.Thread Class defined subclass . #2. Instantiate subclasses and trigger threads . #3. Threading run Method . import threading import datetime exitFlag = 0 class myThread (threading.Thread): def __init__(self, name, counter): threading.Thread.__init__(self) self.threadID = counter self.name = name self.counter = counter def run(self): print("\nStarting " + self.name) # Get lock synchronization thread threadLock.acquire() print_date(self.name, self.counter) # Release the lock for the next thread threadLock.release() print("Exiting " + self.name) def print_date(threadName, counter): datefields = [] today = datetime.date.today() datefields.append(today) print("{}[{}]: {}".format( threadName, counter, datefields[0] )) threadLock = threading.Lock() threads = [] # Create a new thread thread1 = myThread("Thread", 1) thread2 = myThread("Thread", 2) # Start a new thread thread1.start() thread2.start() # Add thread to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to finish for thread in threads: thread.join() print("\nExiting the Program!!!") Copy code
Program output
Starting Thread Thread[1]: 2021-07-22 Exiting Thread Starting Thread Thread[2]: 2021-07-22 Exiting Thread Exiting the Program!!!