gpt4 book ai didi

Redis 实战——不公平信号量

转载 作者:可可西里 更新时间:2023-11-01 11:24:25 25 4
gpt4 key购买 nike

我正在阅读 Redis in action e-book关于semaphores的章节.这是使用redis实现信号量的python代码

def acquire_semaphore(conn, semname, limit, timeout=10):
identifier = str(uuid.uuid4())

now = time.time()

pipeline = conn.pipeline(True)
pipeline.zremrangebyscore(semname, '-inf', now - timeout)

pipeline.zadd(semname, identifier, now)

pipeline.zrank(semname, identifier)
if pipeline.execute()[-1] < limit:

return identifier

conn.zrem(semname, identifier)

return None

This basic semaphore works well—it’s simple, and it’s very fast. But relying on every process having access to the same system time in order to get the semaphore can cause problems if we have multiple hosts. This isn’t a huge problem for our specific use case, but if we had two systems A and B, where A ran even 10 milliseconds faster than B, then if A got the last semaphore, and B tried to get a semaphore within 10 milliseconds, B would actually “steal” A’s semaphore without A knowing it.

我不明白这是什么意思:如果 A 比 B 跑得快 10 毫秒 那么 B 实际上会在 A 不知情的情况下“窃取”A 的信号量。

我的想法:A 的时间是 10:10:10:200,B 的时间是 10:10:10:190,A 有信号量。然后 B 尝试在 10 毫秒内获取信号量(现在 B 的本地时间是 10:10:10:200)。 B 将删除过期的项目并添加它自己。 B 如何窃取 A 的信号量?同时,如果 A 的时间是 10:59,B 的时间是 11:02,则 B 可能会因为时差而删除 A 的信号量。但书中描述的情况并非如此。

最佳答案

如果 B 比 A 慢 10 毫秒,则 B 的分数小于 A,因为我们使用本地时间作为排序集的分数。

所以 B 的排名,即 pipeline.zrank(semname, identifier) , 小于 A 的秩,小于 limit ,即 if pipeline.execute()[-1] < limit: . B 认为它得到了信号量,即 return identifier .事实上,它窃取 A 的信号量。

关于Redis 实战——不公平信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51595786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com