脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python中start和run方法的区别

python中start和run方法的区别

2022-09-24 14:02小槿12358 Python

大家好,本篇文章主要讲的是python中start和run方法的区别,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下

结论:启动线程,如果对target进行赋值,并且没有重写run方法,则线程start的时候会直接调用target中对应的方法

具体代码如下:
1、初始化一个线程

?
1
2
3
4
5
6
7
8
9
10
11
threading.Thread.__init__(self,target=thread_run())
 
def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
        assert group is None, "group argument must be None for now"
        if kwargs is None:
            kwargs = {}
        self._target = target
        self._name = str(name or _newname())
        self._args = args
        self._kwargs = kwargs

2、调用start启动线程
最终调用_start_new_thread方法,self._bootstrap作为传参

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
thread1.start()
    def start(self):
        if not self._initialized:
            raise RuntimeError("thread.__init__() not called")
        if self._started.is_set():
            raise RuntimeError("threads can only be started once")
        with _active_limbo_lock:
            _limbo[self] = self
        try:
            _start_new_thread(self._bootstrap, ())
        except Exception:
            with _active_limbo_lock:
                del _limbo[self]
            raise
        self._started.wait()

3、_start_new_thread等同于启动一个新线程,并在新线程中调用回调函数

?
1
2
_start_new_thread = _thread.start_new_thread
def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ...

4、执行的回调函数就是上文传入的self._bootstrap, _bootstrap方法直接调用_bootstrap_inner(),而bootstrap_inner则调用run方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def _bootstrap_inner(self):
    try:
        self._set_ident()
        self._set_tstate_lock()
        if _HAVE_THREAD_NATIVE_ID:
            self._set_native_id()
        self._started.set()
        with _active_limbo_lock:
            _active[self._ident] = self
            del _limbo[self]
 
        if _trace_hook:
            _sys.settrace(_trace_hook)
        if _profile_hook:
            _sys.setprofile(_profile_hook)
        try:
            self.run()

5、最终调用run方法

?
1
2
3
4
5
6
7
8
def run(self):
       try:
           if self._target:
               self._target(*self._args, **self._kwargs)
       finally:
           # Avoid a refcycle if the thread is running a function with
           # an argument that has a member that points to the thread.
           del self._target, self._args, self._kwargs

结论:
如果run方法被重写,则直接调用重写的run方法
如果run方法没有被重写,并且target被定义,则会直接调用线程创建时候的target方法,否则什么也不做

此处遇到一问题:
指定target参数,在执行过程中,打印的进程名mainthread(主进程),而不是之前所赋的进程名
threading.Thread.init(self,target=thread_run())
分析后发现赋予target的是执行的函数体,因此会先执行thread_run函数,执行结束后,将thread_run的返回值赋给了target,因为thread_run没有返回值,因此target的值是None,如果此时没有重写run函数,那么线程什么都不会做。 thread_run的执行是在主线程,而不是我们所认为的在子线程中执行thread_run

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def thread_run():
    print ("overwrite: 开始线程:" + threading.current_thread().name)
    time.sleep(2)
    print ("overwrite: 退出线程:" + threading.current_thread().name)
 
class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self,target=thread_run())
        self.threadID = threadID
        self.name = name
        self.delay = delay
        thread1.start()
 
thread1.join()
print ("退出主线程")

运行结果:

overwrite: 开始线程:MainThread
overwrite: 退出线程:MainThread
退出主线程

到此这篇关于python中start和run方法的区别的文章就介绍到这了,更多相关python start和run方法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/u011087238/article/details/122896458

延伸 · 阅读

精彩推荐
  • Pythonpython实现五子棋小游戏

    python实现五子棋小游戏

    这篇文章主要介绍了python实现五子棋小游戏,使用pygame模块编写一个五子棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们...

    在校学渣一枚11652021-05-22
  • Python如何利用装饰器实现 Python 函数重载

    如何利用装饰器实现 Python 函数重载

    这篇文章主要介绍了如何利用装饰器实现 Python 函数重载,需要的朋友可以参考下面文章内容,希望能帮助到你...

    豌豆花下猫7702022-01-01
  • PythonPython接口自动化浅析logging日志原理及模块操作流程

    Python接口自动化浅析logging日志原理及模块操作流程

    这篇文章主要为大家介绍了Python接口自动化系列文章浅析logging日志原理及模块操作流程,文中详细说明了为什么需要日志?日志是什么?以及日志用途等基...

    软件测试自动化测试4002021-12-24
  • PythonPython性能优化技巧

    Python性能优化技巧

    Python的批评者声称Python性能低效、执行缓慢,但实际上并非如此:尝试以下6个小技巧,可以加快Pytho应用程序。 ...

    hebedich4022019-11-24
  • PythonPython机器学习NLP自然语言处理基本操作精确分词

    Python机器学习NLP自然语言处理基本操作精确分词

    本文是Python机器学习NLP自然语言处理系列文章,带大家开启一段学习自然语言处理 (NLP) 的旅程. 本文主要学习NLP自然语言处理基本操作之如何精确分词...

    我是小白呀3882022-01-10
  • PythonPython简单删除列表中相同元素的方法示例

    Python简单删除列表中相同元素的方法示例

    这篇文章主要介绍了Python简单删除列表中相同元素的方法,结合具体实例形式分析了Python使用list、set方法针对列表元素的去重与排序操作实现技巧,非常简单...

    JoeBlackzqq4252020-11-17
  • Python详解python之协程gevent模块

    详解python之协程gevent模块

    这篇文章主要介绍了详解python之协程gevent模块,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    嵌动初心(aaron)11732021-03-04
  • Pythonpython 如何通过KNN来填充缺失值

    python 如何通过KNN来填充缺失值

    这篇文章主要介绍了python 通过KNN来填充缺失值的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    六mo神剑12412021-11-09