summaryrefslogtreecommitdiff
path: root/jimbrella/lockfile.py
blob: 987f0e3c7b89086ba752bfa705063ac9e5bf7b8a (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 = str(filepath)
        self.lockpath = self.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