Caffe2 - Python API
A deep learning, cross platform ML framework
file_baton.py
1 from __future__ import absolute_import, division, print_function, unicode_literals
2 import os
3 import sys
4 import time
5 
6 if sys.version < '3.3':
7  # Note(jiayq): in Python 2, FileExistsError is not defined and the
8  # error manifests it as OSError.
9  FileExistsError = OSError
10 
11 
12 class FileBaton:
13  '''A primitive, file-based synchronization utility.'''
14 
15  def __init__(self, lock_file_path, wait_seconds=0.1):
16  '''
17  Creates a new :class:`FileBaton`.
18 
19  Args:
20  lock_file_path: The path to the file used for locking.
21  wait_seconds: The seconds to periorically sleep (spin) when
22  calling ``wait()``.
23  '''
24  self.lock_file_path = lock_file_path
25  self.wait_seconds = wait_seconds
26  self.fd = None
27 
28  def try_acquire(self):
29  '''
30  Tries to atomically create a file under exclusive access.
31 
32  Returns:
33  True if the file could be created, else False.
34  '''
35  try:
36  self.fd = os.open(self.lock_file_path, os.O_CREAT | os.O_EXCL)
37  return True
38  except FileExistsError:
39  return False
40 
41  def wait(self):
42  '''
43  Periodically sleeps for a certain amount until the baton is released.
44 
45  The amount of time slept depends on the ``wait_seconds`` parameter
46  passed to the constructor.
47  '''
48  while os.path.exists(self.lock_file_path):
49  time.sleep(self.wait_seconds)
50 
51  def release(self):
52  '''Releaes the baton and removes its file.'''
53  os.close(self.fd)
54  os.remove(self.lock_file_path)
def __init__(self, lock_file_path, wait_seconds=0.1)
Definition: file_baton.py:15