本文整理汇总了Python中multiprocessing.Value.get_lock方法的典型用法代码示例。如果您正苦于以下问题:Python Value.get_lock方法的具体用法?Python Value.get_lock怎么用?Python Value.get_lock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.Value
的用法示例。
在下文中一共展示了Value.get_lock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Counter
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Counter(object):
"""
A process-safe counter providing atomic incrementAndGet() and value() functions
"""
def __init__(self, initval=0):
"""
Initialize this counter
Args:
initval (int): set the initialize value of the counter
"""
self.val = Value('i', initval)
def incrementAndGet(self):
"""
Atomically increment this counter, and return the new value stored.
Returns:
int: The updated value of this counter.
"""
with self.val.get_lock():
self.val.value += 1
return self.val.value
def value(self):
"""
Atomically get the current value of this counter.
Returns:
int: The current value of this counter.
"""
with self.val.get_lock():
return self.val.value
示例2: Control
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Control(object):
"""Shared (long) value for passing control information between main and
worker threads.
Args:
initial_value: Initial value of the shared control variable.
"""
def __init__(self, initial_value=CONTROL_ACTIVE):
self.control = Value('l', initial_value)
def check_value(self, value, lock=False):
"""Check that the current control value == `value`.
Args:
value: The value to check.
lock: Whether to lock the shared variable before checking.
Returns:
True if the values are equal.
"""
return self.get_value(lock=lock) == value
def check_value_positive(self, lock=False):
"""Check that the current control value is positive.
Args:
lock: Whether to lock the shared variable before checking.
"""
return self.get_value(lock=lock) > 0
def get_value(self, lock=True):
"""Returns the current control value.
Args:
lock: Whether to lock the shared variable before checking.
"""
if lock:
with self.control.get_lock():
return self.control.value
else:
return self.control.value
def set_value(self, value):
"""Set the control value. The shared variable is always locked.
Args:
value: The value to set.
"""
with self.control.get_lock():
self.control.value = value
示例3: __init__
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Counter:
def __init__(self):
self.value = Value(ctypes.c_int)
def __enter__(self):
with self.value.get_lock():
self.value.value += 1
def __exit__(self, exc_type, exc_val, exc_tb):
with self.value.get_lock():
self.value.value -= 1
def __repr__(self):
return str(self.value.value)
示例4: run_with_exception_except_test
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
def run_with_exception_except_test(self):
""" Subclass StoppableExceptionThread and raise exception in method `run_with_exception` """
class IncrementThread(StoppableExceptionThread):
""" Used to test _stop in `run` """
def __init__(self, *args, **kwargs):
self.x = args[0]
StoppableExceptionThread.__init__(self, *args[1:], **kwargs)
def run_with_exception(self):
while not self._stop.is_set():
with self.x.get_lock():
self.x.value += 1
if self.x.value > 5:
raise ValueError('x > 5')
x = Value('i', 0)
st = IncrementThread(x)
st.start()
sleep(1)
assert_equals(st.stopped, False)
with self.assertRaises(ValueError):
st.join()
assert_equals(st.is_alive(), False)
with x.get_lock():
assert_equals(x.value, 6)
示例5: run_stop_test
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
def run_stop_test(self):
""" Subclass StoppableThread and stop method `run` """
class IncrementThread(StoppableThread):
""" Used to test _stop in `run` """
def __init__(self, *args, **kwargs):
self.x = args[0]
super(IncrementThread, self).__init__(*args[1:], **kwargs)
def run(self):
while not self._stop.is_set():
with self.x.get_lock():
self.x.value += 1
x = Value('i', 0)
st = IncrementThread(x)
st.start()
assert_equals(st.stopped, False)
assert_equals(st.is_alive(), True)
sleep(0.5)
st.stop()
assert_equals(st.stopped, True)
st.join()
assert_equals(st.is_alive(), False)
with x.get_lock():
assert_greater(x.value, 0)
示例6: Transformator
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Transformator(Device):
def __init__(self, nomenclature="", width=0., height=0.):
Device.__init__(self, nomenclature, width, height)
self.count = Value('i', 0)
def __repr__(self):
r = str(self) + "("
r += "width=" + str(self.width) + "m, "
r += "height=" + str(self.height) + "m, "
r += "length=" + str(self.length) + "m, "
r += "count=" + str(self.count.value) + ")"
return r
def transport(self, particle):
if not self.is_particle_lost(particle):
with self.count.get_lock():
self.count.value += 1
if self.next:
return self.next.transport(particle)
def reset(self):
self.count.value = 0
if self.next:
self.next.reset()
示例7: Counter
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Counter(object):
def __init__(self):
self.val = Value('i', 0)
def increment(self, n=1):
with self.val.get_lock():
self.val.value += n
@property
def value(self):
return self.val.value
示例8: AtomicCounter
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class AtomicCounter(object):
def __init__(self, init_value=0):
self._val = Value('i', init_value)
def increase(self, incr=1):
with self._val.get_lock():
self._val.value += incr
return self._val.value
def decrease(self, decr=1):
with self._val.get_lock():
self._val.value -= decr
return self._val.value
@property
def value(self):
with self._val.get_lock():
return self._val.value
@property
def lock(self):
return self._val.get_lock()
示例9: run_in_parallel
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
def run_in_parallel(cmds_queue, NPROC):
running_ps = Value("i")
while len(cmds_queue) > 0:
# if we already have the maximum number of processes running,
# then sleep and wait for a process to become free
if running_ps.value >= NPROC:
time.sleep(1)
continue
# get commands to run, and increment the number of processes
# if we can't then we are out of commands, so break
try: cmds = cmds_queue.pop()
except KeyError: break
with running_ps.get_lock():
running_ps.value += 1
# fork a process. If we are still in main, then do nothing. Otherwise,
# run the grabbed commands, decrement the running processes value
# and exit
pid = os.fork()
if pid != 0:
print "FORKED"
continue
else:
print(cmds)
os.system(cmds)
with running_ps.get_lock():
running_ps.value -= 1
os._exit(0)
# wait for outstanding processes to finish
while True:
with running_ps.get_lock():
if running_ps.value == 0: break
time.sleep(1)
continue
return
示例10: Counter
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class Counter(object):
def __init__(self, maximum):
self.max = Value('i', maximum)
self.val = Value('i', 0)
def increment_both(self):
with self.max.get_lock():
self.max.value += 1
return self.increment()
def increment(self, n=1):
with self.val.get_lock():
self.val.value += n
result = self.value
return result
@property
def value(self):
return self.val.value
@property
def maximum(self):
return self.max.value
示例11: count
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class count(object):
def __init__(self, c=0):
self.c = Value('L', c)
def __iter__(self):
return self
def __next__(self):
with self.c.get_lock():
rv = self.c.value
self.c.value += 1
return rv
def next(self):
return self.__next__()
示例12: State
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
class State(object):
def __init__(self):
self.counter = Value('i', 0)
self.start_ticks = Value('d', time.process_time())
def increment(self, n=1):
with self.counter.get_lock():
self.counter.value += n
@property
def value(self):
return self.counter.value
@property
def start(self):
return self.start_ticks.value
示例13: target_except_test
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
def target_except_test(self):
""" propogate exception from target function """
def target_with_exception(x, stop_event):
stop_event.wait(0.5)
while not stop_event.is_set():
with x.get_lock():
x.value += 1
if x.value > 5:
raise ValueError('x > 5')
x = Value('i', 0)
st = StoppableExceptionThread(target=target_with_exception, args=(x,))
st.start()
assert_equals(st.stopped, False)
assert_equals(st.is_alive(), True)
with self.assertRaises(ValueError):
st.join()
assert_equals(st.stopped, False)
assert_equals(st.is_alive(), False)
with x.get_lock():
assert_equals(x.value, 6)
示例14: target_with_args_finishes_test
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
def target_with_args_finishes_test(self):
""" run target function with arguments """
def target_finite(x, stop_event):
stop_event.wait(0.5)
while not stop_event.is_set():
with x.get_lock():
x.value += 1
if x.value > 5:
break
x = Value('i', 0)
st = StoppableExceptionThread(target=target_finite, args=(x,))
st.start()
assert_equals(st.stopped, False)
assert_equals(st.is_alive(), True)
st.join()
assert_equals(st.stopped, False)
assert_equals(st.is_alive(), False)
with x.get_lock():
assert_equals(x.value, 6)
示例15: locks
# 需要导入模块: from multiprocessing import Value [as 别名]
# 或者: from multiprocessing.Value import get_lock [as 别名]
#.........这里部分代码省略.........
"""
self.cq.put( [ self.num, DISPLAY, t ] )
def is_alive( self ):
"""Checks if the child's process is still running, if it is then it returns True, otherwise False.
There's a check for if the process is None, which is set when a child terminates.
:return: Boolean for if Child process is still active (different from if a child is processing data).
"""
if self.proc != None:
return self.proc.is_alive( )
else:
return False
def status( self, type=None ):
"""Uses a multiprocess-safe variable to transmit our status upstream. These values are listed under
universal status types in const.py. The status types allow better logging and, for example, prevent
children that were already terminated from being terminated again (and throwing an exception).
When called with a type it will set this child's status on both the main process and the child's
process. When called without it, it reads from the status variable.
:param None type: The new value of our status.
:returns: If type isn't specified, our status. If it is, it sets our type and returns None.
"""
if type is None:
return self.statusVar.value
else:
with self.statusVar.get_lock( ):
self.statusVar.value = type
def start( self, flag=DISP_LOAD ):
"""Starts our child process off properly, used after a restart typically.
:param DISP_LOAD flag: A custom flag to change the display color of the child, if desired.
:return: None
"""
# Not stopped anymore
self.status( STARTING )
# Create our path
if not os.path.isdir( self.log ):
os.makedirs( self.log )
# Open our handle
self.lh = open( os.path.join( self.log, ''.join( [ 'log-', str( self.num + 1 ), '.txt' ] ) ), 'a+' )
# Show loading
self.display( flag )
# Our process
self.proc = Process( target=self.think, args=( ) )
self.proc.start( )
def restart( self, msg="restarting", flag=None ):
"""Restarts the child process and gets webdriver running again.