Chin的博客

程序的世界多奇妙

用redis实现分布式锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
lock = 0
while lock != 1:
    timestamp = current Unix time + lock timeout + 1
    lock = SETNX lock.foo timestamp
    if lock == 1 or (now() > (GET lock.foo) and now() > (GETSET lock.foo timestamp)):
        break;
    else:
        sleep(10ms)

do_job()

if now() < GET lock.foo:
    DEL lock.foo

Comments