Skip to main content

可以过期的python线程锁,基于python字典实现的锁可以过期

实现方式类似于redis锁过期的实现机制。使用字典代替 redis服务。

安装方式

pip install expire_lock

过期锁用法

import time
from threading import Thread
from expire_lock import ExpireLockConf, ExpireLockContextManager

lockx1_expire = ExpireLockConf(expire_seconds=4, lock_key='test_lock_name_expire', )


def f(x):
    with ExpireLockContextManager(lockx1_expire):
        print(x, time.time())
        time.sleep(5)



for i in range(100):
    Thread(target=f, args=[i]).start()

''''
400秒钟内就把100个函数的print(x)运行完成了, 过期锁的设置 expire=4 和原生锁.acquire(timeout=4) 作用完全不同。

过期锁意思是一个锁获取后,最多能占用这个锁n秒。
原生锁.acquire(timeout=4) 意思是最多只等待这个锁4秒钟,强行获得锁。
'''

和原生线程锁的 lock.acquire(timeout=xx) 完全不一样,原生锁

import time
from threading import Thread, Lock

test_raw_lock = Lock()


def test_raw_lock_fun(x):
    try:
        test_raw_lock.acquire(timeout=4)
        print(x, time.time())
        time.sleep(5)
        test_raw_lock.release()
    except Exception as e:
        if 'release unlocked lock' in str(e):
            return
        print(e)


for i in range(100):
    Thread(target=test_raw_lock_fun, args=[i]).start()


''''
4秒钟内就把100个函数的print(x)运行完成了, 原生锁.acquire(timeout=4) timeout 和 过期锁的4秒过期完全不一样。
'''

Metadata

Release files for expire-lock 0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for expire-lock 0.3
File Size Uploaded
expire_lock-0.3.tar.gz 3.6 kB Details

Release files / expire_lock-0.3.tar.gz

Download URL expire_lock-0.3.tar.gz
Size 3.6 kB
Tags Source
SHA-256 checksum
How to use checksums
0e11118b964eb89178fa6debf721a54073adee8aa5b55d00bd15df591eb8e2b2
BLAKE2b-256 checksum
How to use checksums
8ee145a317c53153f658707f2bf51897769b40045f67161c2f72f8970a63b3d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.12

Release history Release notifications | RSS feed

This release

0.3 This release

1 release file

0.2

1 release file

0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page