python 文件锁simpleflock fcntl

本文介绍了一种利用文件锁来避免数据竞态条件的方法,通过锁定数据修改过程,确保数据一致性,避免并发读取未完成的数据导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、假设场景:

执行某段代码时,产生了一些不想要的结果(称为A),我们会在之后将A修改成想要的结果B;同时,有一个定期监控的流程,一直在读取产生的结果,我们的意图是读取实时读取最新的B,但是有那么一个时刻将A读走,导致错误发生

2、解决办法:

使用文件锁,将产生A以及修改成B的过程加写锁,定期监控加读锁,资源被修改成B的代码拿走时,无法监控读取取

3、代码实现

3.1. simpleflock.py文件锁实现

import time
import os
import fcntl
import errno

class SimpleFlock:
    """Provides the simplest possible interface to flock-based file locking. Intended for use with the `with` syntax. It will create/truncate/delete the lock file as necessary."""

    def __init__(self, path, timeout = None):
        self._path = path
        self._timeout = timeout
        self._fd = None

    def __enter__(self):
        self._fd = os.open(self._path, os.O_CREAT)
        start_lock_search = time.time()
        while True:
            try:
                fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                # Lock acquired!
                return
            except IOError, ex:
                if ex.errno != errno.EAGAIN: # Resource temporarily unavailable
                    raise
                elif self._timeout is not None and time.time() > (start_lock_search + self._timeout):
                    # Exceeded the user-specified timeout.
                    raise

            # TODO It would be nice to avoid an arbitrary sleep here, but spinning
            # without a delay is also undesirable.
            time.sleep(0.1)

    def __exit__(self, *args):
        fcntl.flock(self._fd, fcntl.LOCK_UN)
        os.close(self._fd)
        self._fd = None
        # print 'come to exit'
        # Try to remove the lock file, but don't try too hard because it is
        # unnecessary. This is mostly to help the user see whether a lock
        # exists by examining the filesystem.
        try:
            os.unlink(self._path)
        except:
            pass

if __name__ == "__main__":
    print "Acquiring lock..."
    with SimpleFlock("locktest", 2):
        print "Lock acquired."
        time.sleep(3)
    print "Lock released."

3.2 文件锁使用

print "Acquiring lock..."
    with SimpleFlock("locktest", 2):
        print "Lock acquired."
        time.sleep(3)
    print "Lock released."
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十年23

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值