Python 3 multithreading beginner record

preface

This article is my learning record of learning Python 3 multithreading for the first time. I have a relatively shallow understanding soon after I start learning. I hope you guys will forgive me.

1, Introduction to multithreading

I've been exposed to multithreading since Python 3, and I haven't been exposed to multithreading operations in other languages. Personally, I don't think there should be too many gaps, but I don't dare to judge before learning.

In the actual work of development, one of the problems often encountered is that a certain event needs to be processed for a certain time, but there are other operations that actually do not need to wait for the processing result of this event. Such single line operation leads to low operation efficiency. The way to solve this problem is multithreading.
Each independent thread has an entry to run the program, a sequential execution sequence, and an exit to the program. Moreover, threads cannot execute independently. Threads must exist in the application program, which provides multiple thread execution control.
Each thread has its own set of CPU registers, called the thread context, which reflects the state of the CPU register of the thread last time it ran.
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.
Threads can be divided into kernel threads and user threads.
Python 3 provides two modules to operate on threads:
_ Thread (thread module in the original Python 2)
threading
The threading module contains_ The whole content of thread and its increase, so it is recommended to use this module when learning.
theading module contains the following classes.
Thread: basic thread class
Lock: mutex lock
RLock: reentrant lock, which enables a single process to obtain the held lock again (recursive lock)
Condition: condition lock, which makes one thread wait for another thread to meet specific conditions, such as changing state or a value.
Semaphore: signal lock, which provides a "counter" for limited resources shared between threads. If there are no available resources, it will be blocked.
Event: event lock. Any number of threads wait for an event to occur. After the event occurs, all threads are activated.
Timer: a timer
Barrier: Python3.2. The newly added "blocking" class can only be executed after reaching the specified number of threads.

This article will not introduce how to use each method in each class in detail, but will introduce the basic writing idea of multithreading operation. The specific function details can be obtained by querying the official documents.

2, Two ways to use threads

1. Use function to create thread

This method passes the task function into the thread as a parameter

Examples are as follows:

threading.Thread(target=show, args=(i,))

Note: args must be a tuple

2. Inherit thread class

This method is to create a new thread by inheriting the thread class and overriding the run () method

The following code is an example code on the programming tool:

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Start thread:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("Exit thread:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.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 new thread
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exit main thread")

3, Wire program lock

After introducing the above process, I believe you have realized the power of multithreaded programming, but there is another problem I haven't mentioned so far, and this problem is also the most common problem in multithreaded programming - how to synchronize threads.
As we all know, the cpu calling thread is called randomly. It is possible that the statement of this thread will jump to another statement of another thread in the next instant. Therefore, there is a great possibility of collaboration errors between threads due to dirty data, so there is the concept of thread lock.
Thread lock is a concept introduced to prevent data from being out of sync. Thread lock has two states - locked / unlocked. Whenever a thread needs to access shared data, it must first obtain a lock. However, if the data has been locked by another thread, the thread will pause first, that is, synchronous blocking. After the thread accesses, release the lock, and then let other threads continue.
The following is a code example on the programming lion

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Open thread: " + self.name)
        # Get lock for thread synchronization
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Release the lock and start the next thread
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()
threads = []

# Create a new thread
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Open new thread
thread1.start()
thread2.start()

# Add thread to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
    t.join()
print ("Exit main thread")

Keywords: Python Multithreading

Added by hbsnam on Tue, 04 Jan 2022 05:59:38 +0200