Python thread 14 has a bounded semaphore, which is a semaphore with a bottom line

Official Python column 51, students stop, don't miss this article starting from 0!

In the previous article, the academic committee proposed The idea of making current limiter based on Semaphore semaphore A simple implementation of sum current limiter.

The code is running and seems to have no errors.

However, careful readers will find that if we use semaphores like the following:

xuewei_semaphore.acquire() #Get semaphore
//do something
.... 
xuewei_semaphore.release() #Release semaphore
#>>>  xuewei_semaphore.release() #What if release is called again here?

That is, the release operation of Semaphore is a little more than the acquisition. Will there be a problem?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 10:43 PM, November 27, 2021
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Thunder Science Committee
# @XueWeiTag: CodingDemo
# @File : thread_semaphore_boundvs_unbound.py
# @Project : hello
import threading
import time

xuewei_semaphore = threading.Semaphore(1) #Later, it is changed to bounded semaphore

print("xuewei_semaphore:", xuewei_semaphore)


def run():
    print(" %s ready" % threading.current_thread().name)
    xuewei_semaphore.acquire()
    print(" %s go" % threading.current_thread().name)
    time.sleep(0.1)
    print(" %s completed" % threading.current_thread().name)
    xuewei_semaphore.release()


def abnormal_run():
    run()
    xuewei_semaphore.release()  # One more release


t = threading.Thread(name="Normal use semaphore", target=run)
t.start()
time.sleep(1)
t = threading.Thread(name="Abnormal use semaphore", target=abnormal_run)
t.start()

The above school committee is combined The first article to share semaphores , it is simplified and focuses on the effect of releasing more semaphores.

We found that the program did not report any errors:

What if we add the abnormal use to the call, such as the following code:

#Add the following code after the above code
for i in range(10000):
    t = threading.Thread(name="Abnormal use semaphore"+str(i), target=abnormal_run)
    t.start()

There is no error in the whole process!!!

I was shocked! Python's fault tolerance rate is too high (this is the expression of high Eq, 😂)

The bounded semaphore came and filled the hole

threading.BoundedSemaphore is a bounded semaphore. Its English name is very intuitive.

What is bounded?

Just like being a man, hold the bottom line. So what's the bottom line of Semaphore? We can click on this class to see part of the code.

Semaphore maintains a_ Value, a bounded semaphore is actually adding one more variable_ initial_value to record the initial value of the semaphore.

Later, when we call the release function, the bounded semaphore will be checked every time_ Whether value is out of bounds (that is, once it exceeds _initial_value, a ValueError will be thrown, indicating that it is out of bounds!)

This is too friendly

Here is the bounded semaphore display. Compared with the first code, only

xuewei_semaphore = threading.Semaphore(1)

Replace with:

xuewei_semaphore = threading.BoundedSemaphore(1)

So readers can change it directly. Of course, they can also choose to copy the following code directly and save a file to run.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 10:43 PM, November 27, 2021
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Thunder Science Committee
# @XueWeiTag: CodingDemo
# @File : thread_semaphore_boundvs_unbound3.py
# @Project : hello
import threading
import time

xuewei_semaphore = threading.BoundedSemaphore(1)

print("xuewei_semaphore:", xuewei_semaphore)


def run():
    print(" %s ready" % threading.current_thread().name)
    xuewei_semaphore.acquire()
    print(" %s go" % threading.current_thread().name)
    time.sleep(0.1)
    print(" %s completed" % threading.current_thread().name)
    xuewei_semaphore.release()


def abnormal_run():
    run()
    xuewei_semaphore.release()  # One more release


t = threading.Thread(name="Normal use semaphore", target=run)
t.start()
time.sleep(1)
t = threading.Thread(name="Abnormal use semaphore", target=abnormal_run)
t.start()

After using bounded, sure enough, if it is over released, the system will report an error! Finally relieved.

summary

We should try to use bounded semaphores, which can help us keep the boundary. It will not let the program continue to run normally because we accidentally write the wrong program and write one more release. (it may be that you stay up late to write code, which is not recommended! Writing code requires a comfortable state and higher quality)

If pure Semaphore is used, it must be encapsulated (closed by paired calls) and not open to the use of acquire and release before installation.

For those who like Python, please pay attention to the academic committee Python foundation column or Introduction to Python to master the big column

Continuous learning and continuous development, I'm Lei Xuewei!
Programming is very interesting. The key is to understand the technology thoroughly.
Welcome to wechat, like and support collection!

Keywords: Python Back-end

Added by cottonbuds2005 on Mon, 07 Feb 2022 23:53:41 +0200