程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python multithreading tutorial

編輯:Python

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 .

What are threads 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 .

What is multithreading in computer science ?

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 .

Advantages of multithreading

  • Multithreading can significantly improve the computing speed of multiprocessor or multi-core systems , Because each processor or core processes a separate thread at the same time .
  • Multithreading allows programs to remain responsive while a thread waits for input , At the same time, another thread runs GUI. This statement applies to multiprocessor or uniprocessor systems .
  • All threads of a process can access its global variables . If a global variable changes in a thread , Then it is also visible to other threads . Threads can also have their own local variables .

The disadvantage of multithreading

  • On a single processor system , Multithreading does not affect computing speed . Due to the overhead of managing threads , Performance may drop .
  • Synchronization is required when accessing shared resources to prevent mutual exclusion . It directly leads to more memory and CPU utilization .
  • Multithreading increases the complexity of the program , This makes debugging difficult .
  • It increases the possibility of potential deadlocks .
  • When threads cannot access shared resources regularly , It can cause hunger . The application will not be able to resume its work .

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 Multithreaded modules

Python Two modules are provided to implement threading in the program .

  • ** ** Module and
  • **< Threads > ** modular .

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 .

How to create a thread using the thread module ?

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 .

Basic Python Multithreading example

#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 

How to create a thread using the thread module ?

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

  • threading.activeCount(): It finds the total number . Active thread object .
  • threading.currentThread(): You can use it to determine the number of Thread objects in the caller's thread control .
  • threading.enumerate(): It will give you a complete list of currently active thread objects .

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 .

Steps to implement threads using thread module

You can use the following steps < threading > Module to implement a new thread .

  • from < Thread > Class constructs a subclass .
  • Cover < init(self [,args]) > Method to provide parameters as required .
  • Next , rewrite < run(self [,args]) > Method to write the business logic of the 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 .

Example – Create a thread class to print the date

#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 

Python Multithreading —— Synchronization thread

< 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 .

  • Case Blocking = 0: If the lock acquisition fails , The thread will immediately return a value of zero , If the lock is successful, an .
  • Case Blocking = 1: The thread blocks and waits for the lock to be released .

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 .

Multithreading example of locking

#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!!!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved