Python learning 3 (multithreading)


  1. Using threads, you can put tasks in programs that occupy a long time in the background.
  2. The user interface can be more attractive. For example, if the user clicks a button to trigger the processing of some events, a progress bar can pop up to display the processing progress.
  3. The program will run faster.
  4. In the implementation of some waiting tasks, such as user input, file reading and writing, network sending and receiving data, threads are more useful. In this case, we can release some precious resources, such as memory occupation and so on.

Difference from process

  1. Each independent process has a program entry, sequential execution sequence and program exit. However, threads cannot be executed independently. They must be stored in the application, and the application provides multiple thread execution control.
  2. Each thread has its own set of CPU registers, called the thread context, which reflects the state of the CPU register in which the thread last ran.
  3. Instruction pointer and stack pointer registers are the two most important registers in the thread context. Threads always run in the process context. These addresses are used to mark the memory in the process address space of the thread.
  4. Threads can be preempted (interrupted).
  5. Threads can be suspended (also known as sleep) while other threads are running. This is the concession of threads.

Thread module

  • threading.currentThread(): returns the current thread variable.
  • threading.enumerate(): returns a list of running threads. Running refers to threads after starting and before ending, excluding threads before starting and after termination.
  • threading.activeCount(): returns the number of running threads, with the same result as len(threading.enumerate()).
  • run(): the method used to represent thread activity.
  • start(): start thread activity.
  • join([time]): wait until the thread aborts. 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(): sets the thread name

Create thread
1. Function creation thread

import threading
import time

def test(x):
    time.sleep(3)  # Set to print an x every two seconds
# Create thread t1 and specify parameter 1
t1 = threading.Thread(target=test, args=(1,))
# Create thread t2 and specify parameter 2
t2 = threading.Thread(target=test, args=(2,))
start_time = time.time()
t1.start()# Start thread t1
t2.start()# Start thread t2
print(f"Total operation{time.time() - start_time}second")



2. Class creation thread

class MyThread(threading.Thread):
    def __init__(self,n):
        self.n = n
    def run(self):
        print("Create multithreading as a class",self.n)
r1 = MyThread(11)
r2 = MyThread(22)
start_time = time.time()
print(f"Total operation{time.time()-start_time}second")


Create multithreading 11 as a class
 Creating multithreads as classes 22

Wire program lock

import threading
def run():
    global x #Set all variables
    lock.acquire() #Lock before operating variables
    x += 1
    lock.release()  #Unlock after operating variables

if __name__ == '__main__':
    x = 0 #Define variable x
    res = [] #Definition list
    lock = threading.Lock() #Instantiate a lock object
    #Create multithreading
    for i in range(100):
        t = threading.Thread(target=run)
        res.append(t) #Write list
    for t in res:



Recursive lock

import threading
def run1():
    global x
    lock.acquire()  # Lock before operating variables
    x += 1
    lock.release()  # Unlock after operating variables
    return x

def run2():
    global y
    lock.acquire()  # Lock before operating variables
    y += 1

    lock.release()  # Unlock after operating variables
    return y

def run3():
    lock.acquire()  # Lock before operating variables
    res1 = run1()
    res2 = run2()
    lock.release()  # Unlock after operating variables

if __name__ == '__main__':
    x = 0
    y = 0
    lock = threading.RLock() #Instantiate a lock object
    for i in range(50):
        t = threading.Thread(target=run3)

    while threading.active_count() != 1:
    print('End of thread running!')


Keywords: Python Back-end

Added by micki on Sun, 09 Jan 2022 01:02:05 +0200