We use multithreading to access a resource , But sometimes it is necessary to limit the total number . For example, connection pooling , Support simultaneous connection , But the number is fixed . These connections can use Semaphore To manage .
Let's assume such a scenario :
A restaurant , Only a specified number of people are allowed to eat at the same time , Those who exceed the limit must wait for others to finish their meal .
Code example :
import logging
import random
import time
from threading import Thread, Semaphore
logging.basicConfig(level=logging.DEBUG, format='%(threadName)s-%(asctime)s-%(message)s')
class Restaurant:
def __init__(self, seat_count):
self.seat_count = seat_count # Number of seats
def eating(self):
logging.debug(" During the meal ...")
time.sleep(random.randint(2, 5)) # The meal time is random 2~5 second
logging.debug(" The meal is finished ")
def eating(s: Semaphore, r: Restaurant):
with s:
r.eating()
if __name__ == '__main__':
r = Restaurant(5) # most 5 People eat at the same time
s = Semaphore(r.seat_count) # Limit the number of people eating at the same time to the number of seats
for i in range(10): # 10 Personal meals
t = Thread(target=eating, name=f' customer {
i}', args=(s, r))
t.start()
result :
customer 0-2022-06-27 14:45:30,778- During the meal ...
customer 1-2022-06-27 14:45:30,779- During the meal ...
customer 2-2022-06-27 14:45:30,779- During the meal ...
customer 3-2022-06-27 14:45:30,780- During the meal ...
customer 4-2022-06-27 14:45:30,780- During the meal ...
customer 2-2022-06-27 14:45:33,780- The meal is finished
customer 5-2022-06-27 14:45:33,780- During the meal ...
customer 1-2022-06-27 14:45:34,789- The meal is finished
customer 4-2022-06-27 14:45:34,789- The meal is finished
customer 6-2022-06-27 14:45:34,789- During the meal ...
customer 7-2022-06-27 14:45:34,789- During the meal ...
customer 3-2022-06-27 14:45:35,786- The meal is finished
customer 0-2022-06-27 14:45:35,786- The meal is finished
customer 8-2022-06-27 14:45:35,787- During the meal ...
customer 9-2022-06-27 14:45:35,787- During the meal ...
customer 6-2022-06-27 14:45:37,793- The meal is finished
customer 5-2022-06-27 14:45:38,782- The meal is finished
customer 8-2022-06-27 14:45:39,788- The meal is finished
customer 7-2022-06-27 14:45:39,803- The meal is finished
customer 9-2022-06-27 14:45:40,799- The meal is finished
Pass the result , We can see , There will be at most 5 People eat at the same time , When someone finishes eating , There will be new customers eating soon , Meet our scenario requirements .
Why study python Mainstream pr