不要为每个ban启动一个线程,而是将这些ban放在一个优先级队列中,让一个线程执行休眠和取消扫描
这段代码保留了两个结构:一个是heapq,它可以快速找到最快到期的禁令;另一个是dict,可以快速检查用户是否被姓名禁止import time
import threading
import heapq
class Bans():
def __init__(self):
self.lock = threading.Lock()
self.event = threading.Event()
self.heap = []
self.dict = {}
self.thread = threading.thread(target=self.expiration_thread)
self.thread.setDaemon(True)
self.thread.start()
def ban_user(self, name, duration):
with self.lock:
now = time.time()
expiration = (now+duration)
heapq.heappush(self.heap, (expiration, user))
self.dict[user] = expiration
self.event.set()
def is_user_banned(self, user):
with self.lock:
now = time.time()
return self.dict.get(user, None