summaryrefslogtreecommitdiff
path: root/jimbrella/lockfile.py
blob: b89814272e41a93bee34cb64070ef4f788f82905 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import os


class Lockfile:
    """Prevent unwanted concurrency for file I/O.

    For a file named "<file>", create or remove a lockfile named "<file>.lock".

    When a process is modifying the file, call `lock(). When the modification
    is done, call `unlock()`.
    """

    def __init__(self, filepath):
        self.filepath = filepath
        self.lockpath = filepath + ".lock"

    def lock(self):
        """Continue attempting to lock until locked."""
        locked = False
        while not locked:
            try:
                f = open(self.lockpath, "x")
                f.close()
                locked = True
            except FileExistsError:
                continue

    def unlock(self):
        """Remove lockfile."""
        try:
            os.remove(self.lockpath)
        except FileNotFoundError:
            return