Python implements multithreading

catalogue

1, Semaphore

1. Concept and understanding of semaphore

2. Code example

2, Conditional variable

1. Concept and understanding of conditional variables

2. Correlation function

3. Code example

3, Events

1. Concept and understanding of events

2. Event correlation function

3. Code example

4, Example code demonstration

1. Code example

2. Output sample

5, Reference articles

1, Semaphore

1. Concept and understanding of semaphore

semaphore is a method used by operating system to solve the problems of mutual exclusion and synchronization in concurrency.

The core is to control the number of concurrent threads, which can allow a certain number of threads to change data at the same time.

For example, a semaphore is a value. If n semaphores are given, these semaphores will be given to n threads to run, and the n threads will run at the same time. After the n threads run, some threads will be given, and they will be supplemented to run. In short, each thread can finally run according to the demand in a certain order without delay.

2. Code example

import threading
import time
'''Define a class that inherits threads'''
class MyThread(threading.Thread):
    def run(self):
        '''Lock,If the semaphore is obtained (use acquire Function to determine), and start execution'''
        if semaphore.acquire():
            print(self.name)
            time.sleep(1)
            '''Unlock, release semaphore'''
            semaphore.release()
'''Main function'''
if __name__=="__main__":
    '''To create a lock object, you can use either of the following methods'''
    semaphore = threading.Semaphore(5)
    '''semaphore = threading.BoundedSemaphore(5)'''
    '''Print it out in an array'''
    thrs=[]
    for i in range(100):
        thrs.append(MyThread())
    '''Read out the in the array and then print'''
    for i in thrs:
        i.start()

Output example: execute the process. Since the semaphore parameter passed in by semaphore is 5, the threads are executed in 5. At the same time, insert time packets in the middle and print the time to the console

2, Conditional variable

1. Concept and understanding of conditional variables

Condition is usually associated with a lock. When you need to share a lock among multiple contidions, you can pass a Lock/RLock instance to the constructor, otherwise it will generate an RLock instance itself.

It can be considered that in addition to the Lock pool with Lock, Condition also includes a waiting pool. The threads in the pool are in the waiting blocking state in the state diagram until another thread calls notify()/notifyAll() notification; After being notified, the thread enters the Lock pool and waits for locking.

Or so, Condition provides a multi-threaded communication mechanism. If thread 1 needs data, thread 1 will block and wait. At this time, thread 2 will manufacture data. After thread 2 manufactures the data, thread 2 will notify thread 1 that it can retrieve the data, and then thread 1 will obtain the data.

2. Correlation function

Condition():

  • acquire(): thread lock
  • release(): release the lock
  • wait(timeout): the thread is suspended until it receives a notify notification or timeout (optional, floating-point number, in seconds s) and will not be awakened to continue running. wait() can only be called when Lock has been obtained, otherwise RuntimeError will be triggered.
  • notify(n=1): notify other threads that the suspended threads will start running after receiving this notification. By default, notify a thread waiting for the condition, and wake up n waiting threads at most. notify() can only be called if Lock has been obtained, otherwise RuntimeError will be triggered. notify() does not actively release Lock.
  • notifyAll(): if there are many threads in wait status, notifyAll is used to notify all threads

3. Code example

'''Take producers and consumers as examples'''
import threading
import time

con = threading.Condition()

num = 0

# producer
class Producer(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # Lock thread
        global num
        con.acquire()
        while True:
            print ("Start adding!!!")
            num += 1
            print ("Number of fish balls in hot pot:%s" % str(num))
            time.sleep(1)
            if num >= 5:
                print ("The number of fish balls in the hot pot has reached 5 and can't be added!")
                # Wake up waiting threads
                con.notify()  # Wake up and eat
                # Waiting for notification
                con.wait()
        # Release lock
        con.release()

# consumer
class Consumers(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        con.acquire()
        global num
        while True:
            print("Start eating!!!")
            num -= 1
            print ("Quantity of fish balls left in hot pot:%s" %str(num))
            time.sleep(2)
            if num <= 0:
                print ("The bottom of the pot is out of stock. Add fish balls quickly!")
                con.notify()  # Wake up other threads
                # Waiting for notification
                con.wait()
        con.release()

p = Producer()
c = Consumers()
p.start()
c.start()

Output example:

Start adding!!!
Number of fish balls in hot pot: 1
 Start adding!!!
Number of fish balls in hot pot: 2
 Start adding!!!
Number of fish balls in hot pot: 3
 Start adding!!!
Number of fish balls in hot pot: 4
 Start adding!!!
Number of fish balls in hot pot: 5
 The number of fish balls in the hot pot has reached 5 and can't be added!
Start eating!!!
Quantity of remaining fish balls in hot pot: 4
 Start eating!!!
Quantity of remaining fish balls in hot pot: 3
 Start eating!!!
Quantity of remaining fish balls in hot pot: 2
 Start eating!!!
Quantity of remaining fish balls in hot pot: 1
 Start eating!!!
Quantity of remaining fish balls in hot pot: 0
 The bottom of the pot is out of stock. Add fish balls quickly!
Start adding!!!

3, Events

1. Concept and understanding of events

Event: the mechanism of event processing: a built-in Flag is defined globally. If the Flag value is False, when the program executes event If the Flag value is True, then event The wait method is no longer blocked.

Event is actually a simplified version of Condition. Event has no lock and cannot put the thread into synchronization blocking state.

2. Event correlation function

Event()

  • set(): set the flag to True and notify all threads in the waiting blocking state to resume running state.

  • clear(): set the flag to False.

  • wait(timeout): if the flag is True, it will be returned immediately. Otherwise, the thread will be blocked to the waiting blocking state and wait for other threads to call set().

  • isSet(): gets the built-in flag status and returns True or False.

3. Code example

'''event'''
from threading import Thread,Event
import time
event=Event()
def light():
    print('The red light is on')
    time.sleep(3)
    event.set() #The green light is on
def car(name):
    print('vehicle%s Waiting for the green light' %name)
    event.wait() #When the light is green, event is False until event Set() sets its value to True to continue running
    print('vehicle%s current' %name)
if __name__ == '__main__':
    # traffic lights
    t1=Thread(target=light)
    t1.start()
    # vehicle
    for i in range(10):
        t=Thread(target=car,args=(i,))
        t.start()

Output example:

The red light is on
 Car 0 is waiting for the green light
 Car 1 is waiting for the green light
 Car 2 is waiting for the green light
 Car 3 is waiting for the green light
 Car 4 is waiting for the green light
 Car 5 is waiting for the green light
 Car 6 is waiting for the green light
 Car 7 is waiting for the green light
 Car 8 is waiting for the green light
 Car 9 is waiting for the green light
 Car 1 pass
 Car 2 pass
 Car 4 pass
 Car 9 pass
 Car 8 passes
 Car 5 pass
 Car 3 pass
 Car 7 pass
 Car 0 passes
 Car 6 pass
Process finished with exit code 0

4, Example code demonstration

Example: use class inheritance to realize semaphore and event function operations. Specific case: obtain the current time in the first thread, judge the current time for 3 seconds, and then trigger the "event" object. In another thread, it is used as the judgment variable for the end of the math exam, otherwise it is always in the exam and printed out

1. Code example

'''Use class inheritance to realize semaphore and event function operation. Specific case: the first
 Get the current time in the thread, judge the current time for 3 seconds, and then trigger the "event" object. In another
 In a thread, it is used as the judgment variable for the end of the math exam, otherwise it will always be in the exam and hit
 print'''
import threading
import time
'''Custom event listening class inherits from Thread class'''
class Time(threading.Thread):
    '''Construct methods and override Thread Class constructor initialization self attribute'''
    def __init__(self):
        super(Time, self).__init__()
    '''rewrite Thread Class run method'''
    def run(self):
        for i in range(5):
            '''Output instant time'''
            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            '''Hibernate the thread for 2 seconds'''
            time.sleep(2)
        '''# Set event response ''
        event.set()

'''Custom thread class inherits from Thread class'''
class Exam(threading.Thread):
    '''Construct methods and override Thread Class constructor initialization self attribute'''
    def __init__(self):
        super(Exam, self).__init__()
    '''rewrite Thread Class run method'''
    def run(self):
        '''Loop to determine whether the event responds'''
        while(True):
            print("The exam is in progress, please don't disturb!")
            time.sleep(2)
            if event.is_set():
                print("The exam is over, please stop answering questions!")
                '''And jump out of the loop'''
                break
'''Main function'''
if __name__=='__main__':
    '''initialization event object'''
    event = threading.Event()
    '''#Initialize thread object and call start method ''
    t1 = Exam()
    t1.start()
    et1 = Time()
    et1.start()

2. Output sample

The exam is in progress, please don't disturb!
2022-01-10 10:35:47
 The exam is in progress, please don't disturb!
2022-01-10 10:35:49
 The exam is in progress, please don't disturb!
2022-01-10 10:35:51
 The exam is in progress, please don't disturb!
2022-01-10 10:35:53
 The exam is in progress, please don't disturb!
2022-01-10 10:35:55
 The exam is in progress, please don't disturb!
The exam is over, please stop answering questions!

Process finished with exit code 0

5, Reference articles

python notes 12-python multithreaded event - Shanghai - youyou - blog Park (cnblogs.com)

Keywords: Python Multithreading

Added by marsooka on Mon, 10 Jan 2022 04:50:43 +0200