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

Python multithreading

編輯:Python

List of articles

  • Threads
  • Multithreading

This article will introduce Python The basics of multithreading in programming languages . It's like multitasking , Multithreading is a way to implement multitasking . In multithreading , Use Threads The concept of .

Let's first look at the computer architecture Threads The concept of .

Threads

In calculation , process Is an instance of a computer program being executed . Any process has 3 Basic components :

  • Executable program .
  • Associated data required by the program ( Variable 、 working space 、 Buffer, etc. )
  • The execution context of the program ( Process status )

Threads Is an entity in a process that can be scheduled for execution . Besides , It is available in the operating system ( operating system ) The smallest processing unit executed in .

Simply speaking , Threads Is a sequence of such instructions in a program that can be executed independently of other code . For the sake of simplicity , You can assume that threads are just a subset of processes !

The thread is in Thread control block (TCB) Contains all this information :

  • Thread identifier : Will be the only ID (TID) Assign to each new thread
  • Stack pointer : Point to the thread stack in the process . The stack contains local variables under the thread scope .
  • Program counter : A register that stores the address of the instruction that the thread is currently executing .
  • Thread state : It can be running 、 be ready 、 wait for 、 Start or finish .
  • The register set of the thread : Registers allocated to threads for calculation .
  • Parent process pointer : Point to the process control block of the process where the thread is located (PCB) The pointer to .

Please refer to the following figure to understand the relationship between a process and its threads :

Multithreading

There can be multiple threads in a process , among :

  • Each thread contains its own Register set and local variable ( Stored in the stack ).
  • All threads of the process share Global variables ( Store in the pile ) and Program code .

Refer to the figure below to see how multiple threads exist in memory :

stay Python in , Threads The module provides a very simple and intuitive API, Used to generate multiple threads in a program .

Let's consider a simple example of using a threading module :

import threading
def print_cube(num):
""" A function for printing a cube of a given number """
print("Cube: {}".format(num * num * num))
def print_square(num):
""" Function prints the square of a given number """
print("Square: {}".format(num * num))
if __name__ == "__main__":
# Create thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# Start thread 1
t1.start()
# Start thread 2
t2.start()
# Wait for thread 1 Fully implement
t1.join()
# Wait for thread 2 Fully implement
t2.join()
# Both threads are fully executed
print("Done!")

Running results :

Let's try to understand the above code :

  • To import the thread module , We need to :

    import threading
    
  • To create a new thread , We create a Thread Class object . It requires the following parameters :

    • The goal is : Function to be executed by thread
    • args: Parameters to be passed to the objective function

    In the example above , We created 2 Threads with different objective functions :

    t1 = threading.Thread(target=print_square, args=(10,))
    t2 = threading.Thread(target=print_cube, args=(10,))
    
  • To start a thread , We use Thread Class start Method .

    t1.start()
    t2.start()
    
  • Once the thread starts , Current procedure ( You can think of it as a main thread ) Will continue to carry out . To stop the execution of the current program , Until the thread completes , We use Connect Method .

    t1.join()
    t2.join()
    

    therefore , The current program will first wait t1 Completion , And then wait t2 complete . After completion , The remaining statements of the current program will be executed .

Consider the image below , To better understand how the above procedure works :

Consider the following python Program , Where we print the thread name and the corresponding process for each task :

import threading
import os
def task1():
print(" Mission 1 Assign to thread : {}".format(threading.current_thread().name))
print(" Run the task 1 The process of ID: {}".format(os.getpid()))
def task2():
print(" Mission 2 Assign to thread : {}".format(threading.current_thread().name))
print(" Run the task 2 The process of ID: {}".format(os.getpid()))
if __name__ == "__main__":
# Print the of the current process ID
print(" The process that runs the main program ID: {}".format(os.getpid()))
# Print the main thread name
print(" Main thread name : {}".format(threading.current_thread().name))
# Create thread
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
# Start thread
t1.start()
t2.start()
# Wait for all threads to finish
t1.join()
t2.join()

Running results :

Let's try to understand the above code :

  • We use os.getpid() Function to get the of the current process ID.

    print(" The process that runs the main program ID: {}".format(os.getpid()))
    

    It is clear from the output that , All threaded processes ID All remain the same .

  • We use threading.main_thread() Function to get the main thread object . Under normal circumstances , The main thread is to start Python Interpreter thread . Of Thread objects name Property is used to get the name of the thread .

    print(" Main thread name : {}".format(threading.main_thread().name))
    
  • We use threading.current_thread() Function to get the current thread object .

    print(" Mission 1 Allocated threads : {}".format(threading.current_thread().name))
    

The following figure illustrates the above concepts :


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