python中start和run方法的区别

 更新时间:2022年02月13日 08:57:23   作者:小槿12358  
大家好,本篇文章主要讲的是python中start和run方法的区别,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下

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

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

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作为传参

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等同于启动一个新线程,并在新线程中调用回调函数

_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方法

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方法

 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

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方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python基础之字典

    python基础之字典

    这篇文章主要介绍了python的字典,实例分析了Python中返回一个返回值与多个返回值的方法,需要的朋友可以参考下
    2021-10-10
  • Python pass详细介绍及实例代码

    Python pass详细介绍及实例代码

    这篇文章主要介绍了Python pass详细介绍及实例代码的相关资料,需要的朋友可以参考下
    2016-11-11
  • 用Python的Django框架来制作一个RSS阅读器

    用Python的Django框架来制作一个RSS阅读器

    这篇文章主要介绍了用Python的Django框架来制作一个RSS阅读器,通过url feeds来制作订阅类应用同样是Django之所长,需要的朋友可以参考下
    2015-07-07
  • 使用Python图像处理库Pillow处理图像文件的案例分析

    使用Python图像处理库Pillow处理图像文件的案例分析

    本文将通过使用Python图像处理库Pillow,帮助大家进一步了解Python的基本概念:模块、对象、方法和函数的使用,文中代码讲解的非常详细,需要的朋友可以参考下
    2023-07-07
  • pytorch的batch normalize使用详解

    pytorch的batch normalize使用详解

    今天小编就为大家分享一篇pytorch的batch normalize使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python可变对象,不可变对象详解

    python可变对象,不可变对象详解

    这篇文章主要介绍了Python可变对象和不可变对象的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2021-09-09
  • git使用.gitignore设置不生效或不起作用问题的解决方法

    git使用.gitignore设置不生效或不起作用问题的解决方法

    下面小编就为大家带来一篇git使用.gitignore设置不生效或不起作用问题的解决方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 使用scrapy ImagesPipeline爬取图片资源的示例代码

    使用scrapy ImagesPipeline爬取图片资源的示例代码

    这篇文章主要介绍了使用scrapy ImagesPipeline爬取图片资源的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • python 监测内存和cpu的使用率实例

    python 监测内存和cpu的使用率实例

    今天小编就为大家分享一篇python 监测内存和cpu的使用率实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • Python实现人生重开模拟器小游戏讲解

    Python实现人生重开模拟器小游戏讲解

    这篇文章主要介绍了Python实现人生重开模拟器小游戏,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-01-01

最新评论