本文整理汇总了Python中threading.RLock.acquire方法的典型用法代码示例。如果您正苦于以下问题:Python RLock.acquire方法的具体用法?Python RLock.acquire怎么用?Python RLock.acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.RLock
的用法示例。
在下文中一共展示了RLock.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: XBeeTransparentListener
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class XBeeTransparentListener(Thread):
def __init__(self, xbee_serial):
super().__init__()
self.xbser = xbee_serial
self.daemon = True
self.stopped = False
self.pause = RLock()
def run(self):
while not self.stopped and self.xbser.is_open:
with self.pause:
try:
line = self.xbser.readline()
if line:
print('>', line.strip())
except Exception as ex:
print(str(ex))
def stop(self):
self.stopped = True
def pause(self):
self.pause.acquire()
def unpause(self):
self.pause.release()
示例2: close_dynamic_queue
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
def close_dynamic_queue(self, dynamic_queue_name):
if self._disconnecting:
self.logger.info("Connection factory disconnecting, aborting close_dynamic_queue")
return
else:
self.logger.log(TRACE1, "close_dynamic_queue -> not disconnecting")
if not self._is_connected:
# If we're not connected then all dynamic queues had been already closed.
self.logger.log(TRACE1, "close_dynamic_queue -> _is_connected1 %s" % self._is_connected)
return
else:
self.logger.log(TRACE1, "close_dynamic_queue -> _is_connected2 %s" % self._is_connected)
lock = RLock()
lock.acquire()
try:
dynamic_queue = self._open_dynamic_queues_cache[dynamic_queue_name]
dynamic_queue.close()
self._open_dynamic_queues_cache.pop(dynamic_queue_name, None)
self._open_send_queues_cache.pop(dynamic_queue_name, None)
self._open_receive_queues_cache.pop(dynamic_queue_name, None)
self.logger.log(TRACE1, "Successfully closed a dynamic queue [%s]" % (
dynamic_queue_name))
finally:
lock.release()
示例3: SingleIndexCache
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class SingleIndexCache(object):
def __init__(self):
self.lock = RLock()
self.cached_vals = []
def __enter__(self):
self.lock.acquire()
return self
def fill(self, values):
self.cached_vals = values
def wipe(self):
self.cached_vals = []
def get_index(self, real_funct, ind_name, **kwargs):
kwargs.setdefault("max_results", 999999)
if not self.cached_vals:
recvs = real_funct(ind_name, **kwargs).results
self.fill(recvs)
def filter(self, startkey, endkey, max_results=1):
c = self.cached_vals
for (curr_val, obj_key) in c:
if max_results == 0:
break
if curr_val >= startkey:
if curr_val <= endkey:
max_results -= 1
yield (curr_val, obj_key)
else:
break
def __exit__(self, *args, **kwargs):
self.lock.release()
示例4: Framer
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class Framer(Packer):
HEADER="!4s4B"
def __init__(self, sock):
self.sock = sock
self.sock_lock = RLock()
self.tx_buf = ""
self.rx_buf = ""
self.security_layer_tx = None
self.security_layer_rx = None
self.maxbufsize = 65535
def aborted(self):
return False
def write(self, buf):
self.tx_buf += buf
def flush(self):
self.sock_lock.acquire()
try:
if self.security_layer_tx:
try:
cipher_buf = self.security_layer_tx.encode(self.tx_buf)
except SASLError, e:
raise Closed(str(e))
self._write(cipher_buf)
else:
示例5: VM_Pool
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class VM_Pool(object):
def __init__(self, vm_map):
self.proc_mgr = proc_mgmt.ProcMgr()
self.vm_map = vm_map
self.vm_rdy = {}
self.init_map()
self.pool_gate = RLock()
def acquire(self, *names):
self.pool_gate.acquire()
for name in names:
if self.vm_rdy.get(name):
self.vm_rdy[name] = False
return self.vm_map.get(name)
self.pool_gate.release()
return None
def release(self, name):
self.vm_rdy[name] = True
def init_map(self):
for name, vm_obj in self.vm_map.items():
self.vm_rdy[name] = True
def __str__(self):
string = 'Pool:'
for vm in self.vm_map.keys():
string += vm + ": " + str(self.vm_rdy.get(vm)) + ", "
return string
示例6: resetMysqlMACAndSN
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
def resetMysqlMACAndSN(self,mac):
mysql = MySQLCommand(host=self.sysXMLDict['mysqlhost'], port=int(self.sysXMLDict['mysqlport']),
user=self.sysXMLDict['mysqluser'], passwd=self.sysXMLDict['mysqlpassword'],
db=self.sysXMLDict['mysqldatabase'], table=self.sysXMLDict['mysqltable'])
mysqlConFlag = mysql.connectMysql()
if not mysqlConFlag:
logging.info('reset status connect failed.')
return False
locker = RLock()
locker.acquire()
resetFlag = mysql.resetMysqlMACStatusAndSN(mac=mac,stbType=self.sysXMLDict['mysqlstbtype'], poNumber=self.poNumber)
if resetFlag:
logging.info('reset mysql status success.')
else:
logging.info('reset mysql status failed.')
mysql.closeMysql()
locker.release()
return False
mysql.closeMysql()
locker.release()
return True
示例7: open_dynamic_queue
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
def open_dynamic_queue(self):
if self._disconnecting:
self.logger.info("Connection factory disconnecting, aborting open_dynamic_queue")
return
else:
self.logger.log(TRACE1, "open_dynamic_queue -> not disconnecting")
if not self._is_connected:
self.logger.log(TRACE1, "open_dynamic_queue -> _is_connected1 %s" % self._is_connected)
self._connect()
self.logger.log(TRACE1, "open_dynamic_queue -> _is_connected2 %s" % self._is_connected)
dynamic_queue = self.mq.Queue(self.mgr, self.dynamic_queue_template,
self.CMQC.MQOO_INPUT_SHARED)
# A bit hackish, but there's no other way to get its name.
dynamic_queue_name = dynamic_queue._Queue__qDesc.ObjectName.strip()
lock = RLock()
lock.acquire()
try:
self._open_dynamic_queues_cache[dynamic_queue_name] = dynamic_queue
finally:
lock.release()
self.logger.log(TRACE1, "Successfully created a dynamic queue, descriptor [%s]" % (
dynamic_queue._Queue__qDesc))
return dynamic_queue_name
示例8: ThreadData
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class ThreadData(object):
def __init__(self):
self._data = {}
self._lock = RLock()
def __setitem__(self, key, value):
self._lock.acquire()
thread = current_thread()
if thread not in self._data:
self._data[thread] = {}
self._data[thread][key] = value
self._lock.release()
def __getitem__(self, key):
thread = current_thread()
return self._data[thread][key]
def __delitem__(self, key):
del(self[key])
def __contains__(self, key):
thread = current_thread()
return key in self._data[thread]
def update(self, data):
self._lock.acquire()
thread = current_thread()
self._data[thread].update(data)
self._lock.release()
def clean(self):
thread = current_thread()
if thread in self._data:
del(self._data[thread])
示例9: DataSignaler
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class DataSignaler(object):
def __init__(self, name, pruneFunc, data):
super(DataSignaler, self).__init__()
assert isinstance(data,TreeFunctioned)
self.data = data
self.event_signaler = EventSignaler(key=name)
if pruneFunc is not None:
assert callable(pruneFunc)
self.prune_func = pruneFunc
self._lock = RLock()
def add(self, value):
self._lock.acquire()
try:
self.data.addToTreeByFunction(value)
finally:
self._lock.release()
data = {self.event_signaler.key : {'data': self.data}}
self.event_signaler.signalEvent(data)
def prune(self):
if self.prune_func is not None:
return criticalSection(self._lock, lambda: self.prune_func(dataStructure=self.data))
def inByFunction(self, value, hashFuncList=None, depth=0):
return criticalSection(self._lock, lambda: self.data.inByFunction(value, hashFuncList, depth))
def getOriginalByFunction(self, value, hashFuncList=None, depth=0):
return criticalSection(self._lock, lambda: self.data.getOriginalByFunction(value, hashFuncList, depth))
示例10: PrintingThread
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class PrintingThread(Thread):
def __init__(self, printer, cmds):
log.info("New printing thread, printer %s, len %d" %
(printer, len(cmds)))
self.cmds=cmds
self.printer=printer
self.lock=RLock()
self.state=0
Thread.__init__(self)
def run(self):
printer=self.printer
printer.zero()
from time import time, sleep
from os import path
#wait=time()
#log.info("Waiting for load page button.")
#while path.getmtime(job_dir+"load_new_page")<wait:
# sleep(1.0)
#log.info("Load page button press detected. Starting to print.")
for i, step in enumerate(self.cmds):
printer.do(step)
self.lock.acquire()
self.state=i
self.lock.release()
printer.eject_page()
def progress(self):
self.lock.acquire()
res=self.state
self.lock.release()
return res/float(len(self.cmds)-1)
示例11: TriggerDevice
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class TriggerDevice(NeuroDevice):
def __init__(self, freq = 256, channels = 1):
self.freq = freq
self.channels = channels
self.header = Header(TRIGGER_HEADER)
self.header.channelCount = channels
for i in range(channels):
self.header.channels[i].samplingFrequency = freq
self.header.channels[i].label = 'TRIGGER%d' % i
self.values = [0,]*self.channels
self.valLock = RLock()
self.queue = Queue(15)
self.thread = TriggerDeviceThread(self)
self.thread.start()
def getValues(self):
self.valLock.acquire()
try:
return tuple(self.values)
finally:
self.valLock.release()
def setValues(self, val):
self.valLock.acquire()
try:
self.values[:] = val
finally:
self.valLock.release()
def getHeader(self):
return self.header.text()
def getData(self):
return self.queue.get(10.0)
示例12: CacheDict
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class CacheDict(dict):
_cacheTimeout = 0
_accesslock = None
def __init__(self, timeout):
self._cacheTimeout = timeout
self._accesslock = RLock()
def get(self, key):
return self[key]['value']
def cache(self, key, value):
self[key] = { 'time' : time.time(), 'value' : value }
def isObsolete(self, key):
return (not self.has_key(key) or
time.time() - self[key]['time'] > self._cacheTimeout)
def invalidate(self, key):
if self.has_key(key):
return self.pop(key)['value']
def acquire(self):
self._accesslock.acquire()
def release(self):
self._accesslock.release()
示例13: __init__
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class SimpleCSVWriter:
def __init__(self, filename, fields=None):
self.filename = filename
self.lock = RLock()
self.isFirstRow = True
self.fields = fields
def writerow(self, d):
self.lock.acquire()
fields = self.fields if self.fields is not None else d.keys()
if self.isFirstRow:
# dump fields
f = open(self.filename , "w")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_ALL)
row = [k for k in fields]
writer.writerow(row)
f.close()
self.isFirstRow = False
# dump object
row = [d.get(k,'') for k in fields]
f = open(self.filename , "a")
writer = csv.writer(f, lineterminator="\n", quoting=csv.QUOTE_ALL)
writer.writerow(row)
f.close()
self.lock.release()
示例14: ZenitherClient
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class ZenitherClient():
def __init__(self, robot):
try:
rospy.init_node('ZenitherClient')
rospy.logout('ZenitherServer: Initialized Node')
except rospy.ROSException:
pass
if robot not in zc.calib:
raise RuntimeError('unknown robot')
self.calib = zc.calib[robot]
srv = '/zenither/move_position'
rospy.wait_for_service(srv)
self.move_position = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/stop'
rospy.wait_for_service(srv)
self.stop = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/apply_torque'
rospy.wait_for_service(srv)
self.apply_torque = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/torque_move_position'
rospy.wait_for_service(srv)
self.torque_move_position = rospy.ServiceProxy(srv, Float_Int)
zenither_pose_topic = 'zenither_pose'
self.h = None
self.lock = RLock()
rospy.Subscriber(zenither_pose_topic, FloatArray, self.pose_cb)
#---------- functions to send zenither commands. -------------
def estop(self):
self.stop(0)
def zenith(self, torque=None):
if torque == None:
torque=self.calib['zenith_torque']
self.apply_torque(torque)
def nadir(self, torque=None):
if torque == None:
torque=self.calib['nadir_torque']
self.apply_torque(torque)
#--------- zenither height functions --------------
def pose_cb(self, fa):
self.lock.acquire()
self.h = fa.data[0]
self.lock.release()
## return the current height of the zenither.
def height(self):
self.lock.acquire()
h = self.h
self.lock.release()
return h
示例15: ThreadSafeFSM
# 需要导入模块: from threading import RLock [as 别名]
# 或者: from threading.RLock import acquire [as 别名]
class ThreadSafeFSM(InstrumentFSM):
"""
A FSM class that provides thread locking in on_event to
prevent simultaneous thread reentry.
"""
def __init__(self, states, events, enter_event, exit_event):
"""
"""
super(ThreadSafeFSM, self).__init__(states, events, enter_event, exit_event)
self._lock = RLock()
def on_event(self, event, *args, **kwargs):
"""
"""
self._lock.acquire(True)
ex = None
try:
result = super(ThreadSafeFSM, self).on_event(event, *args, **kwargs)
except Exception as ex:
result = None
log.error("Unhandled Exception")
log.exception(ex)
finally:
self._lock.release()
if ex:
raise ex
return result