zoukankan      html  css  js  c++  java
  • python threading Future源码解析

    1. Future内部还是用了condition这个锁

    2. Cancel

    # future在执行时,会一直更新这个状态    
    def cancel(self):
            """Cancel the future if possible.
    
            Returns True if the future was cancelled, False otherwise. A future
            cannot be cancelled if it is running or has already completed.
            """
            with self._condition:
                if self._state in [RUNNING, FINISHED]:
                    return False
    
                if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                    return True
    
                self._state = CANCELLED
                self._condition.notify_all()
    
            self._invoke_callbacks()
            return True

    2. result

        def result(self, timeout=None):
            """Return the result of the call that the future represents.
    
            Args:
                timeout: The number of seconds to wait for the result if the future
                    isn't done. If None, then there is no limit on the wait time.
    
            Returns:
                The result of the call that the future represents.
    
            Raises:
                CancelledError: If the future was cancelled.
                TimeoutError: If the future didn't finish executing before the given
                    timeout.
                Exception: If the call raised then that exception will be raised.
            """
            with self._condition:
                if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                    raise CancelledError()
                elif self._state == FINISHED:
                    return self.__get_result()
    
                self._condition.wait(timeout)
    
                if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                    raise CancelledError()
                elif self._state == FINISHED:
                    return self.__get_result()
                else:
                    raise TimeoutError()

    3. set_result

        def set_result(self, result):
            """Sets the return value of work associated with the future.
    
            Should only be used by Executor implementations and unit tests.
            """
            with self._condition:
                self._result = result
                self._state = FINISHED
                for waiter in self._waiters:
                    waiter.add_result(self) #通知主线程
                self._condition.notify_all() # 通知其他使用了condition这个锁的,比如result
            self._invoke_callbacks()
  • 相关阅读:
    20201015-3 每周例行报告
    20201008-1 每周例行报告
    20200924-1 每周例行报告
    20200924-3 单元测试,结对
    刷题-Leetcode-120. 三角形最小路径和
    刷题-Leetcode-1025. 除数博弈
    刷题-Leetcode-217. 存在重复元素
    刷题-Leetcode-24.两两交换链表中的节点
    刷题-AcWing-104. 货仓选址
    ARP报文抓包解析实验报告
  • 原文地址:https://www.cnblogs.com/callyblog/p/11148072.html
Copyright © 2011-2022 走看看