directory

  • The Python thread Condition function
  • The Python thread Condition principle
  • The Python thread Condition variable Condition is used
  • A summary of the Python thread Condition variable
  • Five. Guess you like it

Recommended path for learning Python: Python Learning Directory >> Python Basics

Thread-to-thread interaction we’ve covered the Python mutex Lock/Python Event in previous articles. Today we’ll continue with a thread interaction — the thread Condition variable;

The Python thread Condition function

  • Acquire — Thread lock, note that all related function uses in the thread Condition variable must operate inside acquire/release;
  • Release – Releases the lock, noting that all related function uses in the thread Condition variable must operate inside acquire/release;
  • ** WAIT (timeout) ** – A thread is suspended (blocked) and will not resume running until it receives a notify notification or a timeout (the timeout parameter is optional and is of type floating point in seconds). Wait can only be called if a Lock has been obtained, otherwise RuntimeError will be raised.
  • **notify(n=1) ** – Notifies other threads. Suspended threads will start running after receiving this notification. The default parameter is to notify one waiting thread and wake up at most n waiting threads. Notify can only be called when a Lock has been obtained. Otherwise, RuntimeError will be raised and notify will not release the Lock.
  • NotifyAll – If there are many wait threads, notifyAll notifies all threads.

The Python thread Condition principle

The Python mutex Lock protects shared resources from dirty data when they are accessed in parallel.

The Python Condition variable Condition also needs to be associated with a mutex, and Condition itself provides wait/notify/notifyAll methods to block/notify other parallel threads that can access shared resources.

Condition provides a multithreaded communication mechanism. If thread 1 needs data, thread 1 will block and wait, and thread 2 will produce data. When thread 2 has produced data, thread 1 will be notified that it is ready to fetch data.

The Python thread Condition variable Condition is used

Case one: Idiom solitaire

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python thread conditional variable condition. py @time :2021/05/04 07:37 @motto: A thousand miles without a small step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! Condition con = threading.condition () def thread_one(name): Con.acquire () print("{}: format(name)) con.notify() Using WAIT to block the thread, Con. wait() print("{}: nothing ".format(name)) print("{}: nothing ".format(name)) print("{}: nothing ".format(name)) Format (name)) # notify con.notify() # wait for message con.wait() print("{}: wait for message ") print("{}: wait for message ") print("{}: wait for message ") print("{}: wait for message ") Format (name) def thread_two(name) def thread_two(name): Con.wait () print("{}: ready ~ start! ") print("{}: ready ~ start! . The format (name)) # awaken each other con. Notify () # wait for news promised con. Wait () print (" {} : clean your younger sister ah, can't meet... Something simpler..." . The format (name)) # awaken each other con. Notify () # wait for news promised con. Wait () print (" {} : hey, I know: Feet on the ground ". The format (name)) # awaken each other con. Notify () con. Release () if __name__ = = "__main__" : Thread_one (target=thread_one,args=("A")) t2 =thread_two (target=thread_two,args=("B")) # T1.start () t1.start() # block the main thread and wait for the child thread to finish t1.join() t2.join() print(" Program finished! ") A: Are you ready? B: Are you ready? A: Clean out B: Clean out your sister, I can't pick up... Let's do something simple... B: Hey, I know that. Feet on the ground. A: Yay, yay, that's good. End of program! ' ' 'Copy the code

Case 2: producer and consumer model, take eating hot pot as an example: there are 10 pieces of meat in a plate of old meat slices, and then add them to the pot again after eating them… .

  • Producers: Add slices of old meat to the pot, one plate at a time (10 pieces);

  • Consumer: eat cooked meat slices, do not eat a piece, the number of meat slices reduced by one, eat up;

#! Usr/bin/env python # -\_- coding: utF-8 \_\_- "" @author: www.codersrc.com @file :Python thread conditional variable condition. py @time :2021/05/04 07:37 @motto: A thousand miles without a small step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! Condition con = threading.condition () meat_num = 0 def thread_consumers(): Meat_num meat_num = 0 con.wait() while True: meat_num = 0 Print (" I'll have a piece of meat..." Meat_num -= 1 print(" meat_num: %d"%meat_num) time.sleep(0.5) if meat_num == 0: meat_num -= 1 print(" meat_num: %d"%meat_num) time.sleep(0.5) if meat_num == 0: Con.release () def producer() def producer(): Meat_num = 10 print(" meat_num = 10 print(" meat_num = 10 print(" meat_num = 10) Ready to eat..." Meat_num = meat_num = 10 print(" meat_num successfully added! The current number of meat: % d "% meat_num) time. Sleep. (1) con notify () con. Release () if the name * * * * = =" * * * * the main ": T1 = threading.Thread(target=thread_producer) T2 = threading.Thread(target=thread_consumers T1.start () t1.start() # block the main thread and wait for the child thread to finish t1.join() t2.join() print(" Program finished! ") "Output: The meat is cooked and ready to eat... I'll have a piece of meat... Number of slices remaining: 9. I'll have a slice of meat... Number of slices remaining: 8. I'll have a slice of meat... Number of slices remaining: 7 I'll have a slice of meat... Number of slices remaining: 6 I'll have a slice of meat... Number of remaining slices of meat: 5 I'll have a slice of meat... Number of remaining slices of meat: 4 I'll have a slice of meat... Number of slices remaining: 3 I'll have a slice of meat... Number of pieces of meat left: 2. I'll have a piece of meat... Number of pieces of meat left: 1. I'll have a piece of meat... Number of remaining slices of meat: 0 Boss, another slice of old meat... Add fillet meat successfully! Current number of slices: 10 I'll have a slice of meat... Number of slices remaining: 9. I'll have a slice of meat... Number of slices remaining: 8. I'll have a slice of meat... Quantity of remaining meat slices: 7............. ' ' 'Copy the code

Note:

  • 1. Declare the keyword global;
  • 2. Pay attention to the order in which threads are started.

A summary of the Python thread Condition variable

Note the difference between the thread mutex Lock, thread Event, and thread Condition variable. The former two can be used as simple thread interaction, while the thread Condition variable can be used for more complex thread interaction

Five.Guess you like

  1. Python conditional derivations
  2. Python list derivations
  3. Python dictionary derivations
  4. Python function declarations and calls
  5. Python variable argument *argc/**kargcs
  6. Python anonymous function lambda
  7. Python return logic determines expressions
  8. Python string/list/tuple/dictionary conversions
  9. Python local and global variables
  10. The Python type function is different from the isinstance function
  11. Python is differs from ==
  12. Python mutable and immutable data types
  13. Shallow and deep copies of Python
  14. Read and write Python files
  15. Python exception Handling
  16. Python module import
  17. Python __name__ == ‘__main__’ explained in detail

The Python thread Condition variable Condition

This article is published by the blog – Ape Say Programming Ape Say programming!