当前位置: 首页>>代码示例>>Python>>正文


Python Lock.acquire方法代码示例

本文整理汇总了Python中mpx.lib.threading.Lock.acquire方法的典型用法代码示例。如果您正苦于以下问题:Python Lock.acquire方法的具体用法?Python Lock.acquire怎么用?Python Lock.acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mpx.lib.threading.Lock的用法示例。


在下文中一共展示了Lock.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: XCommandIface

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class XCommandIface(TcpConnection):
    def __init__(self, port, host, debug):
        self.__lock = Lock() # lock serializes XCommandIface messaging
        super(XCommandIface, self).__init__(port, host, debug)
        return
        
    def write(self, method_name, params):
        self.__lock.acquire()
        try:
            if not self.connection_ok():
                self.open_connection()
            # marshal data from param tuple
            data = xmlrpclib.dumps(tuple([params]), method_name)
            #payload is 4 byte, little endian, field representing the length of
            #the xml data, followed by the data
            msg = struct.pack('<I', len(data)) + data
            try:
                self._s.send(msg)
            except:
                msglog.log('Adura', ERR, 'Error writing to XCommand socket.')
                raise EConnectionError
            rslt = self.read()
        finally:
            self.close_connection()
            self.__lock.release()
            
    def read(self):
        # leading 4 bytes indicates length of xml-rpc response payload 
        read_len = struct.unpack('<I', self._s.recv(4, timeout=SOCK_OP_TIMEOUT))[0]
        # retreive and marshall the results.  If the xml-rpc packet represents a 
        # fault condition, loads() raises a Fault exception.  @fixme - need a 
        # better understanding of their normal result structure
        rslt = xmlrpclib.loads(self._s.recv(read_len, timeout=SOCK_OP_TIMEOUT))[0]
        return rslt
开发者ID:mcruse,项目名称:monotone,代码行数:36,代码来源:gateway.py

示例2: SocketMap

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class SocketMap(dict):
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
        self.__busy = False
        self.__lock = Lock()
        # The StubNotifier is used during the creation of the real
        # SocketMapNotifier().
        self.__notifier = StubNotifier()
        # Creating the SocketMapNotifier will add it to this SocketMap.
        self.__notifier = SocketMapNotifier(self)
        return
    def wakeup(self, force=False):
        self.__lock.acquire()
        force = force or self.__busy
        try:
            if force:
                self.__notifier.wakeup()
        finally:
            self.__lock.release()
        return
    def __delitem__(self,y):
        self.__lock.acquire()
        try:
            result = dict.__delitem__(self,y)
            if self.__busy:
                self.__notifier.wakeup()
            return result
        finally:
            self.__lock.release()
        raise EUnreachable()
    def __setitem__(self,i,y):
        self.__lock.acquire()
        try:
            result = dict.__setitem__(self,i,y)
            if self.__busy:
                self.__notifier.wakeup()
            return result
        finally:
            self.__lock.release()
        raise EUnreachable()
    def __invoke(self, func, *args):
        self.__lock.acquire()
        self.__busy = True
        self.__lock.release()
        try:
            result = apply(func, args)
        finally:
            self.__lock.acquire()
            self.__busy = False
            self.__lock.release()
        return result
    def poll(self, timeout=0.0):
        return self.__invoke(asyncore.poll, timeout, self)
    def poll2(self, timeout=0.0):
        return self.__invoke(asyncore.poll2, timeout, self)
    def poll3(self, timeout=0.0): 
        return self.__invoke(asyncore.poll3, timeout, self)
    def loop(self, timeout=30.0, use_poll=0):
        return self.__invoke(asyncore.loop, timeout, use_poll, self)
开发者ID:mcruse,项目名称:monotone,代码行数:61,代码来源:socketmap.py

示例3: CANBus

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class CANBus(ARMNode, AutoDiscoveredNode):

    def __init__(self):
        ARMNode.__init__(self)
        AutoDiscoveredNode.__init__(self)
        self._lock = Lock()
        self.conversion_list = {}
        self._queue = Queue()
        self.debug = 0
        self.running = 0
        self._start_called = 0
        self.devices = ''
        self.device_addresses = []
        self._been_discovered = 0

    def lock(self):
        self._lock.acquire()
    def unlock(self):
        self._lock.release()

    ##
    # @see node.ARMNode#configure
    #
    def configure(self,config):
        ARMNode.configure(self,config)

    
    def configuration(self):
        config = ARMNode.configuration(self)
        #get_attribute(self, 'devices', config)
        return config
        

    ##
    # start temperature conversions
    #
    def start(self):
        ARMNode.start(self)
        self.running = 0
    
    def stop(self):
        self.running = 0

    ##
    # discover and create object instances
    #
    def _discover_children(self, force=0):
        if force:
            self._been_discovered = 0
        if self.running == 1 and not self._been_discovered:
            pass
        return self._nascent_children
开发者ID:mcruse,项目名称:monotone,代码行数:54,代码来源:canbus.py

示例4: ExplicitSocketMap

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class ExplicitSocketMap(dict):
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
        self.__lock = Lock()
        self.__notifier = SocketMapNotifier(self)
        return
    def wakeup(self):
        self.__lock.acquire()
        try:
            self.__notifier.wakeup()
        finally:
            self.__lock.release()
        return
开发者ID:mcruse,项目名称:monotone,代码行数:15,代码来源:socketmap.py

示例5: UniqueID

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class UniqueID(PersistentDataObject):
    def __init__(self,node):
        self._lock = Lock()
        self.id = 0
        PersistentDataObject.__init__(self,node)
        self.load()
    def allocate_id(self):
        self._lock.acquire()
        try:
            id = self.id
            self.id += 1
            self.save('id')
        finally:
            self._lock.release()
        return id
开发者ID:mcruse,项目名称:monotone,代码行数:17,代码来源:__init__.py

示例6: __init__

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class _Lock:
    def __init__(self):
        self._minutes = 0
        self._lock = Lock()
        self._scheduled = None
        self._stack = None
    def acquire(self,blocking=0):        
        value = self._lock.acquire(blocking)
        self._stack = traceback.extract_stack()
        self._schedule_print()
        return value
    def release(self):
        try:
            if self._scheduled:
                self._scheduled.cancel()
        finally:
            self._lock.release()
    def locked(self):
        return self._lock.locked()
    def _schedule_print(self):
        self._scheduled = scheduler.after(60,self._print,(self._stack,))
    def _print(self,stack):
        self._minutes += 1
        print 'Lock acquired: %s min' % self._minutes
        print string.join(traceback.format_list(stack))
        if self.locked():
            self._schedule_print()                 
开发者ID:mcruse,项目名称:monotone,代码行数:29,代码来源:auto_discovered_node.py

示例7: TunnelManager

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class TunnelManager(CompositeNode):
    def __init__(self, *args):
        global PTY_DEVS
        self._lock = Lock()
        self._pty_devs = []
        self._ptys_allocated = 0
        module_lock.acquire()
        try:
            if PTY_DEVS is None:
                PTY_DEVS = []
                for major in 'wxyz':
                    for minor in '0123456789abcdef':
                        PTY_DEVS.append('/dev/pty%s%s' % (major, minor))
        finally:
            module_lock.release()
            
    def configure(self, config):
        # vcp_limit is a "hidden" attribute.
        set_attribute(self, 'vcp_limit', 64, config, int)
        CompositeNode.configure(self, config)
        
    def configuration(self):
        config = CompositeNode.configuration(self)
        get_attribute(self, 'vcp_limit', config, str)
        return config
    
    ##
    # Allocate a pseudo-terminal for use by the Port object.
    #
    # @return a string, ie. /dev/ptyr0. 
    def get_pty(self):
        global PTY_DEVS
        self._lock.acquire()
        try:
            while len(PTY_DEVS):
                pty = PTY_DEVS.pop()
                try:
                    # confirm that the pty is accessible.
                    fd = open(pty)
                    fd.close()
                    self._ptys_allocated += 1
                    return pty
                except:
                    pass
            raise EResourceError
        finally:
            self._lock.release()
开发者ID:mcruse,项目名称:monotone,代码行数:49,代码来源:vcp.py

示例8: __init__

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
 class SSL:
     def __init__(self,socket,*args):
         if not isinstance(socket,_Socket):
             raise EInvalidValue('socket',socket,
                                 'Must be mpx.lib.socket.socket')
         self._safety = 0
         if isinstance(socket,_SafetySocket):
             self._safety = 1
         self._socket = socket
         self._ssl = _original_ssl(socket._socket,*args)
         self._lock = Lock()
     def read(self,count=None,timeout=None):
         args = (count,)
         if count is None:
             args = ()
         if ((self._safety or timeout is not None) and 
             not self._socket._wait_readable(0)):
             blocking = self._socket.is_blocking()
             self._lock.acquire()
             try:
                 self._socket.setblocking(0)
                 try:
                     return self._ssl.read(*args)
                 except sslerror,why:
                     if why[0] not in (2,11) and blocking:
                         raise why
             finally:
                 self._socket.setblocking(blocking)
                 self._lock.release()
         else:
             return self._ssl.read(*args)
         if (self._socket._connected and not 
             self._socket._wait_readable(timeout)):
             raise ETimeout('Socket did not become readable')
         return self._ssl.read(*args)
     def write(self,data,timeout=None):
         if ((timeout is not None or self._safety) and 
             self._socket._connected):
             if not self._socket._wait_writable(timeout):
                 raise ETimeout('Socket did not become writable')
         self._lock.acquire()
         try:
             return self._ssl.write(data)
         finally:
             self._lock.release()
     def __getattr__(self,name):
         return getattr(self._ssl,name)
开发者ID:mcruse,项目名称:monotone,代码行数:49,代码来源:socket.py

示例9: KwList

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class KwList(CircList):
    def __init__(self, length):
        super(KwList, self).__init__(length)
        self.__last_ts = time.time()
        self.__last_kwh = None
        self.__lock = Lock()
        return
        
    def add(self, kwh, ts):
        try:
            kwh = float(kwh)
        except:
            return
        if self.__last_kwh is None:
            self.__last_kwh = kwh
        self.__lock.acquire()
        try:
            if kwh < self.__last_kwh or ts < self.__last_ts:
                # either time shifted on us or our kwh rolled\reset.
                self.clear()
            self.__last_ts = ts
            self.__last_kwh = kwh
            self.append(KwEntry(kwh, ts))
        finally:
            self.__lock.release()
        return

    def moving_average(self):
        avg = None
        self.__lock.acquire()
        try:
            if len(self) >= 2:
                 s_kw_entry = self._data[0]
                 e_kw_entry = self._data[-1]
                 delta_s = e_kw_entry.get_ts() - s_kw_entry.get_ts()
                 delta_kwh = e_kw_entry.get_kwh() - s_kw_entry.get_kwh()
                 avg = delta_kwh / self._seconds_as_hours(delta_s)
        finally:
            self.__lock.release()
        return avg

    def _seconds_as_hours(self, seconds):
        return (seconds / 60.0) / 60.0
开发者ID:mcruse,项目名称:monotone,代码行数:45,代码来源:kwh2kw.py

示例10: Consumer

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
 class Consumer(EventConsumerAbstract):
     def __init__(self, *args, **kw):
         EventConsumerAbstract.__init__(self, *args, **kw)
         self.entries = []
         self.errors = []
         self.lock = Lock()
     def event_thread(self,event):
         # The values returned in the event:
         values = event.values
         # The column as read from the source Log instance:
         column_dict = event.source[event.seq]
         # A map of COLUMN_DICT keys to VALUES indexes.
         column_value_map = {
             'timestamp':0, 'reverse':1, 'c2':2, 'c3':3
             }
         # Validate that the list of values matches the actual column in
         # the log:
         for key,index in column_value_map.items():
             if not column_dict.has_key(key):
                 self.errors.append('column_dict has no %r key.' % key)
                 return
             if index >= len(values):
                 self.errors.append('Index(%r) >= len(values:%r).' %
                                    (index, len(values)))
                 return
             if column_dict[key] != values[index]:
                 self.errors.append(
                     'column_dict[%r]:%r != values[%r]:%r' % (
                     key, column_dict[key], index, values[index]))
                 return
         self.lock.acquire()
         try:
             # If any entries are left, the test will fail.
             self.entries.remove(values)
         except:
             # Also, if errors is not empty the test will fail.
             self.errors.append("Failed to find %r in entries." %
                                values)
         self.lock.release()
     def event_handler(self,event):
         t = Thread(target=self.event_thread, args=(event,))
         t.start()
         return
开发者ID:mcruse,项目名称:monotone,代码行数:45,代码来源:_test_case_log.py

示例11: CachedValue

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class CachedValue(CompositeNode):
    def __init__(self):
        self._lock = Lock()
        self._value = _Value()
        CompositeNode.__init__(self)
    def configure(self,config):
        CompositeNode.configure(self,config)
        set_attribute(self, 'expires_after', 0, config, float)
        set_attribute(self, 'node', self.parent, config, as_node)
    def configuration(self):
        config = CompositeNode.configuration(self)
        get_attribute(self, 'expires_after', config, str)
        get_attribute(self, 'node', config, as_node_url)
        return config
    def get(self, skipCache=0):
        self._lock.acquire()
        try:
            if self._value.age() > self.expires_after:
                self._value.set(self.node.get())
        finally:
            self._lock.release()
        return self._value.get()
开发者ID:mcruse,项目名称:monotone,代码行数:24,代码来源:cached_value.py

示例12: mytime

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class mytime(object):
    def __init__(self, systime):
        self._skewlock = Lock()
        self._skewdetected = Event()
        self.base_time_time = systime
        self.base_uptime_time = uptime.secs()
    def notify_detected(self):
        self._skewlock.acquire()
        self._skewdetected.set()
        self._skewlock.release()
    def await_detection(self, timeout = None):
        self._skewlock.acquire()
        self._skewdetected.clear()
        self._skewlock.release()
        return self._skewdetected.wait(timeout)
    def time(self):
        dtime = uptime.secs() - self.base_uptime_time
        comp_time = dtime + self.base_time_time
        if debug:
            print 'mytime.time() returning %f.' % comp_time
        return comp_time
    def skew_base_time(self, skew):
        self.base_time_time = self.base_time_time + skew
开发者ID:mcruse,项目名称:monotone,代码行数:25,代码来源:_test_case_scheduler.py

示例13: AlarmLogger

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class AlarmLogger(ServiceNode):
    def __init__(self):
        self.__lock = Lock()
        ServiceNode.__init__(self)
    def configure(self,config):
        ServiceNode.configure(self,config)
        set_attribute(self,'log',REQUIRED,config)
    def configuration(self):
        config = ServiceNode.configuration(self)
        get_attribute(self,'log',config,as_node_url)
        return config
    def start(self):
        self.log = as_node(self.log)
        ServiceNode.start(self)
    def stop(self):
        self.log = as_node_url(self.log)
        ServiceNode.stop(self)
    def export(self,alarm):
        self.__lock.acquire()
        try:
            self.log.add_entry([time.time(),alarm.source.name,alarm.timestamp,
                                alarm.critical,alarm.values,alarm.message])
        finally:
            self.__lock.release()
开发者ID:mcruse,项目名称:monotone,代码行数:26,代码来源:exporter.py

示例14: _UserDictionary

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class _UserDictionary(PersistentDataObject):
    def __init__(self):
        PersistentDataObject.__init__(self,'mpx.lib.user._UserDictionary')
        self.users = {}
        self.__lock = Lock()
    def has_key(self,name):
        self.__lock.acquire()
        try:
            return self.users.has_key(name)
        finally:
            self.__lock.release()
    def __getitem__(self,name):
        self.__lock.acquire()
        try:
            return self.users[name]
        finally:
            self.__lock.release()
    def __setitem__(self,name,key):
        self.__lock.acquire()
        try:
            self.users[name] = key
            self.save()
        finally:
            self.__lock.release()
开发者ID:mcruse,项目名称:monotone,代码行数:26,代码来源:user.py

示例15: _User

# 需要导入模块: from mpx.lib.threading import Lock [as 别名]
# 或者: from mpx.lib.threading.Lock import acquire [as 别名]
class _User(PersistentDataObject):
    USERS = _UserDictionary()
    def __init__(self,name,new=0,
                 password_file=PASSWD_FILE,group_file=GROUP_FILE,
                 shadow_file = SHADOW_FILE):
        self.__lock = Lock()
        self.__password_file = password_file
        self.__shadow_file = shadow_file
        self.__group_file = group_file
        self.__loaded = 0
        self.__file_modified = 0
        self.load(name)
        self.meta = {}
        self.USERS.load()
        if not self.USERS.has_key(self.name()):
            msglog.log('broadway',msglog.types.INFO,
                       ('No profile for user %s found, creating'
                        ' new profile' % name))
            self.USERS[self.name()] = str(UUID())
        PersistentDataObject.__init__(self,self.USERS[self.name()])
        PersistentDataObject.load(self)
    def loaded(self):
        self.__lock.acquire()
        try:
            return self.__loaded
        finally:
            self.__lock.release()
    def load(self,name):
        self.__lock.acquire()
        try:
            passwd_db = PasswdFile(self.__password_file)
            passwd_db.load()
            if name in passwd_db:
                self.__user = passwd_db[name]
            else:
                self.__user = None
                raise EInvalidValue('name',name,'No such user.')
            self.__file_modified = passwd_db.last_modified()

            # loading /etc/shadow database
            shadow_db = ShadowFile(self.__shadow_file)
            shadow_db.load()
            if name in shadow_db:
                self.__shadow = shadow_db[name]
            else:
                self.__shadow = None
                raise EInvalidValue('User (' ,name, ') does not exist in shadow')
            self.__shadow_file_modified = shadow_db.last_modified()

            self.__loaded = 1
        finally:
            self.__lock.release()
    def reload(self):
        self.load(self.name())
    def save(self):
        self.__lock.acquire()
        try:
            passwd_db = PasswdFile(self.__password_file)
            passwd_db.load()
            passwd_db[self.name()] = self.password_entry()
            passwd_db.save()

            # save /etc/shadow content
            shadow_db = ShadowFile(self.__shadow_file)
            shadow_db.load()
            shadow_db[self.name()] = self.shadow_entry()
            shadow_db.save()
        finally:
            self.__lock.release()
        self.load(self.name())
    def name(self):
        return self.__user.user()
    def password(self):
        raise ENotImplemented(self.password)
    def set_password(self,password, validate=True):
        self.__lock.acquire()
        try:
            shadow_db = ShadowFile(self.__shadow_file)
            shadow_db.load()
            shadowentry = shadow_db[self.name()]
            shadowentry.passwd(password, validate)
            shadow_db[self.name()] = shadowentry
            shadow_db.save()
        finally:
            self.__lock.release()
        self.load(self.name())
    def crypt(self):
        return self.__shadow.crypt()
    def set_crypt(self,crypt):
        self.__shadow.crypt(crypt)
    def uid(self):
        return self.__user.uid()
    def set_uid(self,uid):
        self.__user.uid(uid)
    def gid(self):
        return self.__user.gid()
    def set_gid(self,gid):
        self.__user.gid(gid)
    def group(self):
        return self.__user.groups()[0]
#.........这里部分代码省略.........
开发者ID:mcruse,项目名称:monotone,代码行数:103,代码来源:user.py


注:本文中的mpx.lib.threading.Lock.acquire方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。