論多線程python2與python3


python3 常用線程

# -*- coding: utf-8 -*-
import time
from threading import Thread


def test(i):
    while True:
        print("i",i+1)
        time.sleep(1)
        i+=1
        if i == 5:
            break
print(1)
t = Thread(target=test, args=(0,))
#
t.setDaemon(True)
t.start()
print("---",2)

主線程一直運行,遇到循環耗時操作分出子線程,主線程運行到最后等待子線程結束,再進行關閉

 

 

python2.7 thread方法

# -*- coding: utf-8 -*-
import time
# from threading import Thread
import thread

def test(i):
    while True:
        print "i",i+1
        time.sleep(1)
        i+=1
        if i == 5:
            break
print 1
thread.start_new_thread(test, (0,))
# t = Thread(target=test, args=(0,))
# t.start()
print "---",2

主線程運行到最后就結束,相當於python3中設置了守護進行,如上注釋部分所示


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM