• 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()
  • 相关阅读:
    vector的erase函数
    结构体定义容易混淆的地方
    JavaScript重点知识
    JS中预解析案例分析
    浏览器console控制台不显示编译错误/警告
    强烈推荐一款强大的公式编辑器软件AxMath
    DIV+CSS布局
    CSS-常见属性
    CSS-定义样式表
    CSS-使用CSS样式的方式
  • 原文地址:https://www.cnblogs.com/callyblog/p/11148072.html
Copyright © 2020-2023  润新知