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


Python WeakKeyDictionary.items方法代码示例

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


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

示例1: EventListener

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class EventListener(threading.Thread):
    def __init__(self, *args, **kargs):
        super(EventListener, self).__init__(*args, **kargs)
        self.queue = mp.Queue()   ## queue to receive message
        self.task_queue = mp.JoinableQueue()
        self.listener_proc = EventListenerProc(self.task_queue,
                                               self.queue)
        wx.CallAfter(self.listener_proc.start)
        self.viewers = WeakKeyDictionary()
    def run(self, *args, **kargs):
        while True:
#            try:
            event_name = self.queue.get(True)
            if event_name == 'stop':
#                from ifigure.mdsplus.mdsscope import scope_count
#                if scope_count == 0:
                globals()['listener_thread'] = None
                return
            mds_event_listener_lock.acquire()
            check = False
            ll = list(self.viewers.items()) ##protecting weakdictionary
            for v in self.viewers:
               if event_name in self.viewers[v]:
                  evt = wx.PyCommandEvent(MDSEventReceived, 
                                       wx.ID_ANY)
                  evt.mdsevent_name = event_name
                  try:
                      wx.PostEvent(v, evt)
                  except:
                      check = True
                      pass
            del ll
            if check: del self.viewers[v]

            mds_event_listener_lock.release()
开发者ID:piScope,项目名称:piScope,代码行数:37,代码来源:event_listener.py

示例2: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    def __init__(self):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()

    def __call__(self, *args, **kargs):
        for f in self._functions:
            f(*args, **kargs)

        for obj, functions in self._methods.items():
            for f in functions:
                f(obj, *args, **kargs)

    def connect(self, slot):
        if inspect.ismethod(slot):
            if not slot.__self__ in self._methods:
                self._methods[slot.__self__] = set()
            self._methods[slot.__self__].add(slot.__func__)
        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)
开发者ID:BaxterTU2014,项目名称:baxter_interface,代码行数:30,代码来源:signals.py

示例3: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    """
    Simple class to emit signals to connected callable receivers.
    """

    def __init__(self):
        """
        Instantiate a new object
        """
        self.funcs = WeakSet()
        self.meths = WeakKeyDictionary()

    def connect(self, c):
        """
        Connect a callable as receiver for the signal
        @param c: signal receiver
        @type c: Callable
        """
        if inspect.ismethod(c):
            if c.__self__ not in self.meths:
                self.meths[c.__self__] = set()

            self.meths[c.__self__].add(c.__func__)
        else:
            if c not in self.funcs:
                self.funcs.add(c)

    def disconnect(self, c):
        """
        Disconnect the callable from receiving the signal
        @param c: signal receiver
        @type c: Callable
        """
        if inspect.ismethod(c):
            if c.__self__ in self.meths:
                self.meths[c.__self__].remove(c.__func__)
        else:
            if c in self.funcs:
                self.funcs.remove(c)

    def disconnectAll(self):
        """
        Disconnects all signal receivers
        """
        self.funcs.clear()
        self.meths.clear()

    def emit(self, *args, **kwargs):
        """
        Fires the signal to all connected receivers
        """
        for c in self.funcs:
            c(*args, **kwargs)

        for obj, funcs in self.meths.items():
            for func in funcs:
                func(obj, *args, **kwargs)
开发者ID:pathmann,项目名称:pyTSon,代码行数:59,代码来源:signalslot.py

示例4: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    def __init__(self):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()
        self._activated = True

    def __call__(self, *args, **kargs):

        # call connected functions only if activated
        if self._activated:
            # Call handler functions
            for func in self._functions:
                func(*args, **kargs)

            # Call handler methods
            for obj, funcs in self._methods.items():
                for func in funcs:
                    func(obj, *args, **kargs)

    def connect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        self._functions.clear()
        self._methods.clear()

    def activate(self):
        """
        Activate the signal to emit.
        """

        self._activated = True

    def deactivate(self):
        """
        Deactivate the signal to emit.
        """

        self._activated = False
开发者ID:ElricleNecro,项目名称:LISA,代码行数:56,代码来源:Signals.py

示例5: Game

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Game(object):
    global MIN_PLAYERS
    MIN_PLAYERS = 2
    def  __init__(self):
        self.players = WeakKeyDictionary()
        
    def addPlayer(self, player):
        #player.paddle = PongPadle()
        self.players[player.uuid] = player
        
    def removePlayer(self, player):
        del self.players[player.uuid]
    
    def numberOfPlayers(self):
        return len(self.getPlayers())
    
    def isPlayer(self, player):
        return self.players[player]
    
    def getOpponents(self, player):
        opponents = []
        for p in self.players.items():
            if(p[1].uuid != player.uuid):
                opponents.append(p[1])
        return opponents
    
    def minPlayersConnected(self):
        if self.numberOfPlayers() >= MIN_PLAYERS:
            return True
        else:
            return False
    
    def getPlayers(self):
        allPlayers = []
        for p in self.players.items():
            allPlayers.append(p[1])
        return allPlayers
    
    def update(self):
        raise NotImplementedError("Please Implement this method")
开发者ID:borgaster,项目名称:GameServerClient,代码行数:42,代码来源:Game.py

示例6: EvalTaskRunner

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class EvalTaskRunner(MetaDataTool):
    def __init__(self):
        super(EvalTaskRunner, self).__init__(
            ['eval_task_results'],
            dict(eval_task_results=WeakKeyDictionary())
        )
        self.threads = WeakKeyDictionary()

    def add_chunk(self, chunk, old_meta_data, new_meta_data):
        tasks = [(ch, old_meta_data['eval_tasks'][ch]) \
                    for ch in old_meta_data['eval_tasks'] \
                        if ch not in new_meta_data['eval_task_results']]

        # create threads for the tasks and run them in parallel
        for chunk_, task_ in tasks:
            # wait for a running thread to terminate
            running = [th for ch, th in self.threads.items() if th.isAlive()]
            while len(running) >= 8:
                for th in running:
                    if not th.isAlive():
                        running.remove(th)
                        break
                if running:
                    running[0].join(0.01)

            # create and start new thread
            th = EvaluatorThread(task_, chunk_, old_meta_data)
            th.start()
            self.threads[chunk_] = th

        # retrieve results
        for ch, th in self.threads.items():
            th.join()
            new_meta_data['eval_task_results'][ch] = th.result

        self.threads = WeakKeyDictionary()
开发者ID:shoemark,项目名称:yaweb,代码行数:38,代码来源:eval.py

示例7: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    def __init__(self):
        # The original implementation used WeakSet to store functions,
        # but that causes lambdas without any other reference to be
        # garbage collected. So we use a normal set to avoid that.
        self._functions = set()
        self._methods = WeakKeyDictionary()

    # The original implementation used __call__, so one would just call the signal itself:
    #
    # my_signal("foo")
    #
    # This has been changed to the emit() method to both be more consistent with how signals/slots
    # work in Qt & GTK and to make it more easily apparent that a signal is being triggered.
    # The correct way to trigger a signal is therefore:
    #
    # my_signal.emit("foo")
    def emit(self, *args, **kargs):
        # Call handler functions
        for func in self._functions:
            func(*args, **kargs)

        # Call handler methods
        for obj, funcs in self._methods.items():
            for func in funcs:
                func(obj, *args, **kargs)

    def connect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        self._functions.clear()
        self._methods.clear()
开发者ID:rvykydal,项目名称:anaconda,代码行数:50,代码来源:signal.py

示例8: SIGNAL

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class SIGNAL(object):
    
    def __init__( self, name = None ):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()
        self._name = name

    def __call__(self, *args, **kargs):
        # Call handler functions
        for func in self._functions:
            func(*args, **kargs)

        # Call handler methods
        for obj, funcs in self._methods.items():
            for func in funcs:
                func(obj, *args, **kargs)

    def connect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        self._functions.clear()
        self._methods.clear()
开发者ID:charlesdoutriaux,项目名称:uvcdat-devel,代码行数:40,代码来源:ConfigurationFunctions.py

示例9: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    def __init__(self):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()

    def __call__(self, *args, **kargs):
        res = []
        # Call handler functions
        for func in self._functions:
            res.append(func(*args, **kargs))

        # Call handler methods
        for obj, funcs in self._methods.items():
            for func in funcs:
                res.append(func(obj, *args, **kargs))
        return res

    def connect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        self._functions.clear()
        self._methods.clear()
开发者ID:kittykat,项目名称:hotdoc,代码行数:40,代码来源:simple_signals.py

示例10: Mediator

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Mediator(object):
    """this object is responsible for coordinating most communication
    between the Model, View, and Controller."""
    def __init__(self):
        self.listeners = WeakKeyDictionary()
        self.eventQueue= []
        self.debug = True

    def registerListener(self, listener):
        """
        @type listener: Controller
        @param listener: The name of the listener to register
        """
        self.listeners[listener] = 1

    def unregisterListener(self, listener):
        """
        @type listener: Controller
        @param listener: The name of the listener to unregister
        """
        if listener in self.listeners:
            del self.listeners[listener]

    def post(self, event):
        """
        Notify the registered listeners to a event

        @type event: Event
        @param event: Event to trigger
        """
        listeners = self.listeners.items()

        for listener in listeners:
            listener[0].notify(event)

        del listeners
开发者ID:rubenspgcavalcante,项目名称:pygameoflife,代码行数:38,代码来源:mediator.py

示例11: emit

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal:
    ##  Signal types.
    #   These indicate the type of a signal, that is, how the signal handles calling the connected
    #   slots.
    #   - Direct connections immediately call the connected slots from the thread that called emit().
    #   - Auto connections will push the call onto the event loop if the current thread is
    #     not the main thread, but make a direct call if it is.
    #   - Queued connections will always push
    #     the call on to the event loop.
    Direct = 1
    Auto = 2
    Queued = 3

    ##  Initialize the instance.
    #
    #   \param kwargs Keyword arguments.
    #                 Possible keywords:
    #                 - type: The signal type. Defaults to Auto.
    def __init__(self, **kwargs):
        self.__functions = WeakSet()
        self.__methods = WeakKeyDictionary()
        self.__signals = WeakSet()
        self.__type = kwargs.get("type", Signal.Auto)

        self.__emitting = False
        self.__connect_queue = []
        self.__disconnect_queue = []

    ##  \exception NotImplementedError
    def __call__(self):
        raise NotImplementedError("Call emit() to emit a signal")

    ##  Get type of the signal
    #   \return \type{int} Direct(1), Auto(2) or Queued(3)
    def getType(self):
        return self.__type

    ##  Emit the signal which indirectly calls all of the connected slots.
    #
    #   \param args The positional arguments to pass along.
    #   \param kwargs The keyword arguments to pass along.
    #
    #   \note If the Signal type is Queued and this is not called from the application thread
    #   the call will be posted as an event to the application main thread, which means the
    #   function will be called on the next application event loop tick.
    @call_if_enabled(_traceEmit, _isTraceEnabled())
    def emit(self, *args, **kwargs):
        try:
            if self.__type == Signal.Queued:
                Signal._app.functionEvent(CallFunctionEvent(self.emit, args, kwargs))
                return

            if self.__type == Signal.Auto:
                if threading.current_thread() is not Signal._app.getMainThread():
                    Signal._app.functionEvent(CallFunctionEvent(self.emit, args, kwargs))
                    return
        except AttributeError: # If Signal._app is not set
            return

        self.__emitting = True

        # Call handler functions
        for func in self.__functions:
            func(*args, **kwargs)

        # Call handler methods
        for dest, funcs in self.__methods.items():
            for func in funcs:
                func(dest, *args, **kwargs)

        # Emit connected signals
        for signal in self.__signals:
            signal.emit(*args, **kwargs)

        self.__emitting = False
        for connector in self.__connect_queue:
            self.connect(connector)
        self.__connect_queue.clear()
        for connector in self.__disconnect_queue:
            self.disconnect(connector)
        self.__connect_queue.clear()

    ##  Connect to this signal.
    #   \param connector The signal or slot (function) to connect.
    @call_if_enabled(_traceConnect, _isTraceEnabled())
    def connect(self, connector):
        if self.__emitting:
            # When we try to connect to a signal we change the dictionary of connectors.
            # This will cause an Exception since we are iterating over a dictionary that changed.
            # So instead, defer the connections until after we are done emitting.
            self.__connect_queue.append(connector)
            return

        if isinstance(connector, Signal):
            if connector == self:
                return
            self.__signals.add(connector)
        elif inspect.ismethod(connector):
            if connector.__self__ not in self.__methods:
                self.__methods[connector.__self__] = set()
#.........这里部分代码省略.........
开发者ID:TimurAykutYildirim,项目名称:Uranium,代码行数:103,代码来源:Signal.py

示例12: __init__

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]

#.........这里部分代码省略.........

    @lockmethod
    def add_context(self, context, path, as_parent):
        #print("add context", path, context, as_parent, context._mount["persistent"])
        paths = self.paths[context._root()]
        if not as_parent:
            if context not in self.contexts:
                assert path not in paths, path
                paths.add(path)
                self.contexts.add(context)
        else:
            if path in paths:
                assert context in self.contexts, (path, context)        

    def _check_context(self, context, as_parent):
        mount = context._mount
        assert not is_dummy_mount(mount), context
        dirpath = mount["path"].replace("/", os.sep)
        persistent, authority = mount["persistent"], mount["authority"]
        if os.path.exists(dirpath):
            if authority == "cell" and not as_parent:
                print("Warning: Directory path '%s' already exists" % dirpath) #TODO: log warning
        else:
            if authority == "file-strict":
                raise Exception("Directory path '%s' does not exist, but authority is 'file-strict'" % dirpath)
            os.mkdir(dirpath)

    @lockmethod
    def add_cell_update(self, cell):
        if self._mounting:
            return
        assert cell in self.mounts, (cell, hex(id(cell)))
        self.cell_updates.append(cell)

    def _run(self):
        for cell, mount_item in list(self.mounts.items()):
            if isinstance(cell, Link):
                continue
            if cell in self.cell_updates:
                continue
            try:
                mount_item.conditional_read()
            except Exception:
                exc = traceback.format_exc()
                if exc != mount_item.last_exc:
                    print(exc)
                    mount_item.last_exc = exc
        while 1:
            try:
                cell = self.cell_updates.popleft()
            except IndexError:
                break
            mount_item = self.mounts.get(cell)
            if mount_item is None: #cell was deleted
                continue
            try:
                mount_item.conditional_write(with_none=True)
            except Exception:
                exc = traceback.format_exc()
                if exc != mount_item.last_exc:
                    print(exc)
                    mount_item.last_exc = exc
        self._tick.set()

    def run(self):
        try:
            self._running = True
            while not self._stop:
                t = time.time()
                self._run()
                while time.time() - t < self.latency:
                    if not self._tick.is_set():
                        break
                    time.sleep(0.01)
        finally:
            self._running = False

    def start(self):
        self._stop = False
        t = self.thread = Thread(target=self.run)
        t.setDaemon(True)
        t.start()

    def stop(self, wait=False, waiting_loop_period=0.01):
        self._stop = True
        if wait:
            while self._running:
                time.sleep(waiting_loop_period)

    def tick(self):
        """Waits until one iteration of the run() loop has finished"""
        if self._running:
            self._tick.clear()
            self._tick.wait()

    def destroy(self):
        for path in list(self.mounts.keys()):
            self.unmount(path)
        for context in sorted(self.contexts,key=lambda l:-len(l.path)):
            self.unmount_context(context)
开发者ID:sjdv1982,项目名称:seamless,代码行数:104,代码来源:mount.py

示例13: NotificationManager

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class NotificationManager(Thread):
    def __init__(self, registry, *args, **kw):
        super(NotificationManager, self).__init__(*args, **kw)
        self.__pending = WeakKeyDictionary()
        #TODO: Locking needed here?
        self.__lock = Lock()
        self.__registry = registry
        self.__queue = Queue()
        self.__running = True
        
    def notify(self, condition, owner, reference):
        try:
            entry = self.__registry.resolve_payload_entry(owner)
            self.__enqueue(condition, entry, reference)
            self.__queue.put(owner)
        except:
            logger.exception("Failed to resolve owner for notification: " + str(owner))
        
    def __do_notify(self, condition, owner, entry, reference):
        if entry.is_available:
            left = condition
            shadow = self.__registry.shadow_manager.get_shadow(entry.payload)
            for c in condition:
                try:
                    shadow.notify(c, owner, reference)
                    left = left & (~c)
                except CommunicationError:
                    logger.exception("unable to notify " + str(shadow))
                    break
                
                if not left:
                    return
                condition = NotificationId(left)
    
        self.__enqueue(condition, entry, reference)
        
    def __enqueue(self, condition, owner_entry, reference):
        logger.debug("queuing message")
        with self.__lock:
            for c in condition:
                val = (c, reference)
                try:
                    queue = self.__pending[owner_entry]
                    if val not in queue:
                        queue.append(val)
                except KeyError:
                    self.__pending[owner_entry] = [ val ]
                
    def remove_reference(self, reference):
        with self.__lock:
            for owner_entry, queue in self.__pending.items():
                for c, r in tuple(queue):
                    if r == reference:
                        queue.remove((c, r))
                
                if not queue:
                    self.__pending.pop(owner_entry, None)

    def join(self, timeout = None):
        self.__running = False
        super(NotificationManager, self).join(timeout)

    def run(self):
        while self.__running:
            try:
                owner_entry = None
            except (SystemExit, KeyboardInterrupt):
                self.__running = False
            except:
                logger.exception("Error during notify loop")
开发者ID:tubav,项目名称:teagle,代码行数:72,代码来源:NotificationManager.py

示例14: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class Signal(object):
    """ class for signal slot concept

    Example
    -------

    A simple example for a callback is
    >>> event = Signal()
    >>> event.connect(mfunc)
    >>> # raise the signal
    >>> event("hello")
    >>>
    >>> # functions can be disconnected
    >>> even.disconnect(myfunc)

    Since weak references are used, care has to be taken with object functions

    >>> obj = MyClass()
    >>> event.connect(obj.myfunc) # works
    >>> event.connect(MyClass().myfunc) # will not work

    The second example for member functions will not work since the Signal class
    uses weakref and therefore does not increase the reference counter. MyClass()
    only exists for the time of the function call and will be deleted afterwards
    and the weakref will become invalid.

    """
    
    def __init__(self):
        self._functions = WeakSet()
        self._methods = WeakKeyDictionary()

    def __call__(self, *args, **kargs):
        """ raise the event """
        # Call handler functions
        for func in self._functions:
            func(*args, **kargs)

        # Call handler methods
        for obj, funcs in self._methods.items():
            for func in funcs:
                func(obj, *args, **kargs)

    def connect(self, slot):
        """ connect a function / member function to the signal """
        if inspect.ismethod(slot):
            if slot.__self__ not in self._methods:
                self._methods[slot.__self__] = set()

            self._methods[slot.__self__].add(slot.__func__)

        else:
            self._functions.add(slot)

    def disconnect(self, slot):
        """ disconnect a function from the signal """
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)

    def clear(self):
        """ remove all callbacks from the signal """
        self._functions.clear()
        self._methods.clear()
开发者ID:pele-python,项目名称:pele,代码行数:69,代码来源:events.py

示例15: ScriptManager

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import items [as 别名]
class ScriptManager(object):

    def __init__(self):
        self._lock = RLock()
        self._threads = WeakKeyDictionary()
        self._cleaner = None

    def work(self):
        now = time()
        with self._lock:
            for thread, (overall, counter, deadline) in list(self._threads.items()):
                if counter and now > deadline:
                    log.warning("Terminate %s due to timeout" % describe_thread(thread))
                    ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, ctypes.py_object(ScriptTimeoutError))
                    self._threads.pop(thread, None)

    def start_cleaner(self):
        with self._lock:
            if self._cleaner is None:
                self._cleaner = ScriptCleaner(self)
                self._cleaner.start()
            return self._cleaner

    def ignore(self):
        ctypes.pythonapi.PyThreadState_SetAsyncExc(current_thread().ident, None)

    def constrain(self, overall):
        thread = current_thread()
        with self._lock:
            values = self._threads.get(thread)
            if values is None:
                self._threads[thread] = overall, 0, None

    def revoke(self):
        thread = current_thread()
        with self._lock:
            try:
                overall, counter, deadline = self._threads[thread]
            except KeyError:
                pass
            else:
                if counter:
                    self._threads[thread] = None, counter, deadline
                else:
                    del self._threads[thread]

    def watch(self, timeout=settings.SCRIPT_TIMEOUT):
        thread = current_thread()
        with self._lock:
            overall, counter, deadline = self._threads.get(thread, (None, 0, None))
            if deadline is None:
                self._threads[thread] = overall, counter + 1, time() + (overall or timeout)
            else:
                self._threads[thread] = overall, counter + 1, deadline

            if self._cleaner is None:
                self.start_cleaner()

    def leave(self):
        thread = current_thread()
        with self._lock:
            try:
                overall, counter, deadline = self._threads[thread]
            except KeyError:
                pass
            else:
                if counter == 1 and overall is None:
                    del self._threads[thread]
                else:
                    self._threads[thread] = overall, counter - 1, deadline

    def prolong(self, value):
        thread = current_thread()
        with self._lock:
            try:
                overall, counter, deadline = self._threads[thread]
            except KeyError:
                pass
            else:
                self._threads[thread] = overall, counter, deadline + value
开发者ID:VDOMBoxGroup,项目名称:runtime2.0,代码行数:82,代码来源:manager.py


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