pytorch
1# mypy: allow-untyped-defs
2import os
3import time
4
5
6class FileBaton:
7"""A primitive, file-based synchronization utility."""
8
9def __init__(self, lock_file_path, wait_seconds=0.1):
10"""
11Create a new :class:`FileBaton`.
12
13Args:
14lock_file_path: The path to the file used for locking.
15wait_seconds: The seconds to periodically sleep (spin) when
16calling ``wait()``.
17"""
18self.lock_file_path = lock_file_path
19self.wait_seconds = wait_seconds
20self.fd = None
21
22def try_acquire(self):
23"""
24Try to atomically create a file under exclusive access.
25
26Returns:
27True if the file could be created, else False.
28"""
29try:
30self.fd = os.open(self.lock_file_path, os.O_CREAT | os.O_EXCL)
31return True
32except FileExistsError:
33return False
34
35def wait(self):
36"""
37Periodically sleeps for a certain amount until the baton is released.
38
39The amount of time slept depends on the ``wait_seconds`` parameter
40passed to the constructor.
41"""
42while os.path.exists(self.lock_file_path):
43time.sleep(self.wait_seconds)
44
45def release(self):
46"""Release the baton and removes its file."""
47if self.fd is not None:
48os.close(self.fd)
49
50os.remove(self.lock_file_path)
51