combo_lock.py
Go to the documentation of this file.
1 # Copyright 2018 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 from threading import Lock
16 from fasteners.process_lock import InterProcessLock
17 from os.path import exists
18 from os import chmod
19 
20 
21 class ComboLock:
22  """ A combined process and thread lock.
23 
24  Arguments:
25  path (str): path to the lockfile for the lock
26  """
27  def __init__(self, path):
28  # Create lock file if it doesn't exist and set permissions for
29  # all users to lock/unlock
30  if not exists(path):
31  f = open(path, 'w+')
32  f.close()
33  chmod(path, 0o777)
34  self.plock = InterProcessLock(path)
35  self.tlock = Lock()
36 
37  def acquire(self, blocking=True):
38  """ Acquire lock, locks thread and process lock.
39 
40  Arguments:
41  blocking(bool): Set's blocking mode of acquire operation.
42  Default True.
43 
44  Returns: True if lock succeeded otherwise False
45  """
46  if not blocking:
47  # Lock thread
48  tlocked = self.tlock.acquire(blocking=False)
49  if not tlocked:
50  return False
51  # Lock process
52  plocked = self.plock.acquire(blocking=False)
53  if not plocked:
54  # Release thread lock if process couldn't be locked
55  self.tlock.release()
56  return False
57  else: # blocking, just wait and acquire ALL THE LOCKS!!!
58  self.tlock.acquire()
59  self.plock.acquire()
60  return True
61 
62  def release(self):
63  """ Release acquired lock. """
64  self.plock.release()
65  self.tlock.release()
66 
67  def __enter__(self):
68  """ Context handler, acquires lock in blocking mode. """
69  self.acquire()
70  return self
71 
72  def __exit__(self, _type, value, traceback):
73  """ Releases the lock. """
74  self.release()
def __exit__(self, _type, value, traceback)
Definition: combo_lock.py:72
def acquire(self, blocking=True)
Definition: combo_lock.py:37


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40