我是靠谱客的博主 疯狂雪糕,最近开发中收集的这篇文章主要介绍python 文件锁simpleflock fcntl,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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."

最后

以上就是疯狂雪糕为你收集整理的python 文件锁simpleflock fcntl的全部内容,希望文章能够帮你解决python 文件锁simpleflock fcntl所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部