账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    python 中的主线程 和子线程的关系
    20
    0
    #coding=utf-8
    import threading
    from time import ctime,sleep
    def music(func):
        for i in range(2):
            print "I was listening to %s. %s" %(func,ctime())
            sleep(1)
    
    def move(func):
        for i in range(2):
            print "I was at the %s! %s" %(func,ctime())
            sleep(1)
    
    threads = []
    t1 = threading.Thread(target=music,args=(u'爱情买卖',))
    threads.append(t1)
    t2 = threading.Thread(target=move,args=(u'阿凡达',))
    threads.append(t2)
    if __name__ == '__main__':
        for t in threads:
            t.setDaemon(True)
            t.start()
    
    
        print "all over %s" %ctime()
        
        
        
        

    这里的 print "all over %s" %ctime() 是主线程?为啥?
    为啥python2和python3 执行的结果不一样呢?

    python 2:
    I was listening to 爱情买卖. Thu Dec 14 19:28:49 2017
    all over Thu Dec 14 19:28:49 2017
    python3:
    I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 离心痛  η° 普通会员 1楼

      在Python中,主线程和子线程是两个独立的概念。

      主线程是Python的守护线程,它负责控制程序的执行顺序。当你运行Python程序时,实际上是在执行Python程序中的多个子线程。这些子线程共享Python的全局解释器锁(GIL),这使得它们可以并行执行。

      子线程是Python中的独立线程,它们可以在Python的多核处理器上运行。子线程不需要Python的全局解释器锁,因此它们可以并行执行,但可能会受到多核处理器性能的影响。

      需要注意的是,Python的全局解释器锁(GIL)的存在并不是完全阻止了子线程的并行执行。在某些情况下,GIL可以帮助提高程序的性能,特别是在多核处理器上。然而,在大多数情况下,Python的GIL会阻止多线程的并行执行,因为线程之间的同步和通信是通过全局解释器锁来实现的。

    更多回答
    网站公告
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部