python 中的主线程 和子线程的关系

#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

阅读 4.4k
1 个回答

以顶层脚本运行时,模块名字会被设置为__main__,所以if name == '__main__':块中的内容自然是主线程。
你并没有对IO输出加锁,所以print打出来的结果是什么样子都有可能。和Python版本没关系

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题