f | from collections import deque | f | from collections import deque |
| | | |
| class Lock: | | class Lock: |
| busy = {} | | busy = {} |
| sems = {} | | sems = {} |
| | | |
| def __init__(self, par): | | def __init__(self, par): |
| self.par = par | | self.par = par |
| self._lock = None | | self._lock = None |
| self.sem = None | | self.sem = None |
| | | |
| def __str__(self): | | def __str__(self): |
| return str(self.par) | | return str(self.par) |
| | | |
| @property | | @property |
| def lock(self): | | def lock(self): |
| if self.sem not in Lock.busy: | | if self.sem not in Lock.busy: |
| for k, v in Lock.sems.items(): | | for k, v in Lock.sems.items(): |
| if self.par in v: | | if self.par in v: |
| self._lock = self.sem | | self._lock = self.sem |
| Lock.busy[self.sem] = self.par | | Lock.busy[self.sem] = self.par |
n | elif self.par != Lock.busy[self.sem]: | n | elif self.par == Lock.busy[self.sem]: |
| | | pass |
| | | else: |
| self._lock = None | | self._lock = None |
| return self._lock | | return self._lock |
| | | |
| @lock.setter | | @lock.setter |
| def lock(self, value): | | def lock(self, value): |
n | busy = Lock.busy.items() | n | tmp = Lock.busy.items() |
| for k, v in busy: | | for k, v in tmp: |
| if self.par == v: | | if self.par == v: |
| del Lock.busy[k] | | del Lock.busy[k] |
| break | | break |
| for k, v in Lock.sems.items(): | | for k, v in Lock.sems.items(): |
| if self.par in v: | | if self.par in v: |
| Lock.sems[k].remove(self.par) | | Lock.sems[k].remove(self.par) |
| break | | break |
| self.sem = value | | self.sem = value |
| try: | | try: |
| Lock.sems[value].append(self.par) | | Lock.sems[value].append(self.par) |
| except: | | except: |
| Lock.sems[value] = deque([self.par]) | | Lock.sems[value] = deque([self.par]) |
| | | |
| @lock.deleter | | @lock.deleter |
| def lock(self): | | def lock(self): |
n | busy = Lock.busy.items() | n | tmp = Lock.busy.items() |
| for k, v in busy: | | for k, v in tmp: |
| if self.par == v: | | if self.par == v: |
| del Lock.busy[k] | | del Lock.busy[k] |
| break | | break |
| for k, v in Lock.sems.items(): | | for k, v in Lock.sems.items(): |
| if v: | | if v: |
| if self.par == v[0]: | | if self.par == v[0]: |
| Lock.sems[k].popleft() | | Lock.sems[k].popleft() |
| | | |
| def __del__(self): | | def __del__(self): |
n | busy = Lock.busy.items() | n | tmp = Lock.busy.items() |
| for k, v in busy: | | for k, v in tmp: |
| if self.par == v: | | if self.par == v: |
| del Lock.busy[k] | | del Lock.busy[k] |
| break | | break |
| for k, v in Lock.sems.items(): | | for k, v in Lock.sems.items(): |
| if self.par in v: | | if self.par in v: |
| Lock.sems[k].remove(self.par) | | Lock.sems[k].remove(self.par) |
| | | |
| def locked(self): | | def locked(self): |
t | | t | |
| | | class locked_class(Lock): |
| | | pass |
| return Lock | | return locked_class |