Python thread semaphore semaphore - Python zero basics tutorial

Posted by slapdashgrim on Sun, 23 Jan 2022 18:02:01 +0100

catalogue

Zero basic Python learning route recommendation: Python learning directory >> Getting started with Python Basics

I Introduction to Python thread semaphore

Through front face Thread mutex lock / Thread event / Thread condition variable condition / Thread timer I believe you have a certain understanding of the threading module. Executing multiple threads at the same time can indeed improve the efficiency of the program, but the more threads, the better. It may not have much impact on the computer if you run 20 ~ 30 threads directly. What if you run thousands or even tens of thousands of threads at the same time? I believe your computer will be directly paralyzed

II Python thread semaphore semaphore principle

Multithreading Running at the same time can improve the running efficiency of the program, but not the more threads the better. The semaphore semaphore can control the number of threads running at the same time through the built-in counter. The built-in counter of starting thread * * (semaphore consumption) will automatically decrease by one, and the built-in counter of thread end (semaphore release) * * will automatically increase by one; If the built-in counter is zero, the starting thread will block until this thread ends or other threads end;

III Introduction to Python thread semaphore function

  • **acquire * * - semaphore consumption, built-in counter minus one;
  • **Release * * - release semaphore, and the built-in counter is incremented by one;

There is a built-in counter in the semaphore semaphore to control the number of threads. Acquire will consume the semaphore, and the counter will automatically decrease by one; Release will release the semaphore and the counter will automatically increase by one; When the counter is zero, the acquire call is blocked until release releases the semaphore.

IV Python thread semaphore usage

Create multiple threads and limit up to 5 threads to run at the same time. The example code is as follows:

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python Thread semaphore semaphore.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 module
import time

# Add a counter. The maximum number of concurrent threads is 5 (up to 5 threads running at the same time)
semaphore = threading.Semaphore(5)

def foo():
    semaphore.acquire()    #Counter acquire lock
    time.sleep(2)   #Program sleep for 2 seconds
    print("Current time:",time.ctime()) # Print current system time
    semaphore.release()    #Counter release lock


if __name__ == "__main__":

    thread_list= list()
    for i in range(20):
        t=threading.Thread(target=foo,args=()) #Create thread
        thread_list.append(t)
        t.start()  #Start thread

    for t in thread_list:
        t.join()

    print("The program is over!")


'''
Output result:

Current time: Tue May  4 12:01:43 2021
 Current time: Tue May  4 12:01:43 2021
 Current time: Tue May  4 12:01:43 2021
 Current time: Tue May  4 12:01:43 2021
 Current time: Tue May  4 12:01:43 2021
 Current time: Tue May  4 12:01:45 2021
 Current time: Tue May  4 12:01:45 2021
 Current time: Tue May  4 12:01:45 2021
 Current time: Tue May  4 12:01:45 2021
 Current time: Tue May  4 12:01:45 2021
 Current time: Tue May  4 12:01:47 2021
 Current time: Tue May  4 12:01:47 2021
 Current time: Tue May  4 12:01:47 2021
 Current time: Tue May  4 12:01:47 2021
 Current time: Tue May  4 12:01:47 2021
 Current time: Tue May  4 12:01:49 2021
 Current time: Tue May  4 12:01:49 2021
 Current time: Tue May  4 12:01:49 2021
 Current time: Tue May  4 12:01:49 2021
 Current time: Tue May  4 12:01:49 2021
 The program is over!

Process finished with exit code 0

'''

According to the printed log, only five threads run at the same time. After an interval of two seconds, start five threads again until all 20 threads run; If semaphore Semapaore is not set and the thread is directly started, the output time is the same. This problem is relatively simple. You can experiment it yourself!

V Guess you like it

  1. Python conditional derivation
  2. Python list derivation
  3. Python dictionary derivation
  4. Python function declarations and calls
  5. Python indefinite length parameter * argc/**kargcs
  6. Python anonymous function lambda
  7. Python return logical judgment expression
  8. Conversion between Python Strings / lists / tuples / Dictionaries
  9. Python local and global variables
  10. Difference between Python type function and isinstance function
  11. Python is and = = difference
  12. Python variable and immutable data types
  13. Python shallow and deep copies
  14. Python file read / write operation
  15. Python exception handling
  16. Python module import
  17. Python __name__ == ‘__ main__’ explicate

No reprint without permission: Ape programming ยป Python thread semaphore

Topics: Python