catalogue
- I Python thread Condition variable Condition function
- II Python thread Condition variable principle
- III Python thread Condition variable Condition use
- IV Python thread Condition variable Condition summary
- V Guess you like it
Zero basic Python learning route recommendation: Python learning directory >> Getting started with Python Basics
For the interaction between threads, we have introduced it in the previous article Python mutex Lock / Python Event Today, we will continue to introduce a thread interaction method – Thread Condition variable;
I Python thread Condition variable Condition function
- Acquire - thread lock. Note that all related functions in the thread Condition variable Condition must be operated inside acquire / release;
- Release - release the lock. Note that all related functions in the thread Condition variable Condition must be operated inside acquire / release;
- **wait (timeout) * * - the thread is suspended (blocked). It will not be awakened until it receives a notify notification or timeout to continue running (the timeout parameter is not set by default, optional, the type is floating point number, and the unit is seconds). wait can be called only after Lock has been obtained, otherwise RuntimeError will be triggered;
- **notify(n=1) * * - notify other threads. Those suspended threads will start running after receiving this notification. The default parameter is to notify a thread waiting for notification by default, and wake up n waiting threads at most. Notify can only be called when Lock has been obtained, otherwise RuntimeError will be triggered, and notify will not actively release Lock;
- NotifyAll - if there are many threads in the wait state, notifyAll is used to notify all threads;
II Python thread Condition variable principle
Python mutex Lock is mainly used to protect shared resources and prevent dirty data when accessing shared resources in parallel.
Python Conditional variable Condition The mutex also needs to be associated. At the same time, the Condition itself provides wait / notify / notifyAll methods to block / notify other parallel threads that can access shared resources.
It can be understood that Condition provides a Multithreading 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 fetch the data, and then thread 1 will obtain the data.
III Python thread Condition variable Condition use
Case 1: idiom Solitaire
# !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:Ape programming @Blog(Personal blog address): www.codersrc.com @File:Python Thread condition variable Condition.py @Time:2021/05/04 07:37 @Motto:No small steps can lead to thousands of miles, no small streams can lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly! """ # Import thread module import threading # Create condition variable condition con = threading.Condition() def thread_one(name): # Condition variable condition thread lock con.acquire() print("{}:Are Jackie Chan ready".format(name)) # Wake up the thread waiting con.notify() # Wait for the response message from the other party, block the thread with wait, and wait for the other party to wake up the thread through notify con.wait() print("{}:clean out completely".format(name)) # Wake each other up con.notify() # Wait for message promise con.wait() print("{}:One day, you know, look at the jockey girl, here's a simple one for you: tiktok.".format(name)) # Wake each other up con.notify() # Wait for message promise con.wait() print("{}:Yo, yo, good!".format(name)) # Wake each other up con.notify() # Condition variable condition thread releases lock con.release() def thread_two(name): # Condition variable condition thread lock con.acquire() # wait for other threads to wake up this thread through notify con.wait() print("{}:be ready~Let's go!".format(name)) # Wake each other up con.notify() # Wait for message promise con.wait() print("{}:Jing, your sister, I can't answer...Let's have a simpler one...".format(name)) # Wake each other up con.notify() # Wait for message promise con.wait() print("{}:well,I know this: down to earth".format(name)) # Wake each other up con.notify() con.release() if __name__ == "__main__": # Create and initialize threads t1 = threading.Thread(target=thread_one,args=("A")) t2 = threading.Thread(target=thread_two,args=("B")) # Start thread -- pay attention to the start sequence of threads. The start sequence is very important t2.start() t1.start() # Block the main thread and wait for the child thread to end t1.join() t2.join() print("The program is over!") ''' Output results: A:Are Jackie Chan ready B:be ready~Let's go! A:clean out completely B:Jing, your sister, I can't answer...Let's have a simpler one... A:One day, you know, look at the jockey girl, here's a simple one for you: tiktok. B:well,I know this: down to earth A:Yo, yo, good! The program is over! '''
Case 2: producer consumer model. Take hot pot as an example: there are 10 pieces of meat in a plate of old meat. After eating, add it to the pot again
- Producer: add old meat slices to the pot, one plate at a time (10 pieces);
- Consumer: eat cooked meat slices. If you don't eat one slice, the number of meat slices will be reduced by one until you finish eating;
# !usr/bin/env python # -_- coding:utf-8 \__- """ @Author:Ape programming @Blog(Personal blog address): www.codersrc.com @File:Python Thread condition variable Condition.py @Time:2021/05/04 07:37 @Motto:No small steps can lead to thousands of miles, no small streams can lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly! """ # Import thread module import threading import time # Create condition variable condition con = threading.Condition() meat_num = 0 def thread_consumers(): # Condition variable condition thread lock con.acquire() # global variable declaration keyword global global meat_num meat_num = 0 # Wait until the meat slices are cooked con.wait() while True: print("I'll have a piece of meat...") meat_num -= 1 print("Quantity of remaining meat slices:%d"%meat_num) time.sleep(0.5) if meat_num == 0: # When the meat slices are eaten up, inform the boss to add meat slices print("Boss, another slice of old meat...") con.notify() # The meat is eaten up. Wait for the meat con.wait() # Condition variable condition thread releases lock con.release() def thread_producer(): # Condition variable condition thread lock con.acquire() # global variable declaration keyword global global meat_num # The sliced meat is ripe and ready to eat meat_num = 10 print("The sliced meat is ripe and ready to eat...") con.notify() while True: # Blocking function, waiting for the notification that the meat slice is finished con.wait() meat_num = 10 # After adding meat slices, you can continue to eat print("Meat slices added successfully! Current number of meat slices:%d"%meat_num) time.sleep(1) con.notify() con.release() if **name** == "**main**": # Create and initialize threads t1 = threading.Thread(target=thread_producer) t2 = threading.Thread(target=thread_consumers) # Start thread -- pay attention to the starting sequence of threads. The starting sequence is very important t2.start() t1.start() # Block the main thread and wait for the child thread to end t1.join() t2.join() print("The program is over!") ''' Output results: The sliced meat is ripe and ready to eat... I'll have a piece of meat... Quantity of remaining meat slices: 9 I'll have a piece of meat... Quantity of remaining meat slices: 8 I'll have a piece of meat... Quantity of remaining meat slices: 7 I'll have a piece of meat... Quantity of remaining meat slices: 6 I'll have a piece of meat... Quantity of remaining meat slices: 5 I'll have a piece of meat... Quantity of remaining meat slices: 4 I'll have a piece of meat... Quantity of remaining meat slices: 3 I'll have a piece of meat... Quantity of remaining meat slices: 2 I'll have a piece of meat... Quantity of remaining meat slices: 1 I'll have a piece of meat... Number of remaining meat slices: 0 Boss, another slice of old meat... Meat slices added successfully! Current number of meat slices: 10 I'll have a piece of meat... Quantity of remaining meat slices: 9 I'll have a piece of meat... Quantity of remaining meat slices: 8 I'll have a piece of meat... Quantity of remaining meat slices: 7 ............. '''
be careful:
- 1. Global variables should declare the keyword global;
- 2. Pay attention to the starting sequence of threads, which is very important;
IV Python thread Condition variable Condition summary
Pay attention to the differences between thread mutex Lock / thread Event / thread Condition variable. The first two can be used as simple thread interaction in different scenarios, and the thread Condition variable can be used for more complex thread interaction
V Guess you like it
- Python conditional derivation
- Python list derivation
- Python dictionary derivation
- Python function declarations and calls
- Python indefinite length parameter * argc/**kargcs
- Python anonymous function lambda
- Python return logical judgment expression
- Conversion between Python Strings / lists / tuples / Dictionaries
- Python local and global variables
- Difference between Python type function and isinstance function
- Python is and = = difference
- Python variable and immutable data types
- Python shallow and deep copies
- Python file read / write operation
- Python exception handling
- Python module import
- Python __name__ == ‘__ main__’ explicate
No reprint without permission: Ape programming » Python thread Condition variable Condition