/usr/lib/python3/dist-packages/molotov/sharedcounter.py is in python3-molotov 1.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | import multiprocessing
class SharedCounter(object):
"""A multi-process compatible counter.
"""
def __init__(self, name):
self._val = multiprocessing.Value('i', 0)
self._name = name
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def __ge__(self, other):
return self.__cmp__(other) >= 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __cmp__(self, other):
if isinstance(other, SharedCounter):
other = other.value
if not isinstance(other, int):
raise TypeError(other)
if self._val.value == other:
return 0
elif self._val.value > other:
return 1
return -1
def __repr__(self):
return '<SharedCounter %d>' % self._val.value
def __iadd__(self, other):
self.__add__(other)
return self
def __isub__(self, other):
self.__sub__(other)
return self
def __add__(self, other):
with self._val.get_lock():
if isinstance(other, SharedCounter):
other = other.value
if not isinstance(other, int):
raise NotImplementedError()
self._val.value += other
def __sub__(self, other):
self.__add__(-other)
@property
def value(self):
return self._val.value
@value.setter
def value(self, _value):
with self._val.get_lock():
if isinstance(_value, SharedCounter):
_value = _value.value
if not isinstance(_value, int):
raise TypeError(_value)
self._val.value = _value
class SharedCounters(object):
"""Mapping of SharedCounter items.
"""
def __init__(self, *keys):
self._counters = {}
for key in keys:
self._counters[key] = SharedCounter(key)
def items(self):
return self._counters.items()
def values(self):
return self._counters.values()
def __iter__(self):
return self._counters.__iter__()
def keys(self):
return self._counters.keys()
def __contains__(self, key):
return key in self._counters
def __repr__(self):
return repr(self._counters)
def __setitem__(self, key, value):
if key not in self._counters:
raise KeyError(key)
self._counters[key].value = value
def __getitem__(self, key):
return self._counters[key]
|