開啓線程的兩種方式

#線程開啓一
from threading import Thread
import time
def sayhi(name):
    time.sleep(2)
    print('%s say hello'%name)
if __name__ == '__main__':
    t = Thread(target=sayhi,args=('egon',))
    t.start()       #剛剛開啓就調用,由於還睡了兩秒,因此先執行主線程
    print('主線程')

  

#開啓線程方式二
from threading import Thread
import time
class Sayhi(Thread):
    def __init__(self,name):
        super().__init__()
        self.name = name
    def run(self):     #名字必須爲run
        time.sleep(2)
        print('%s say hello'%self.name)
if __name__ == '__main__':
    t = Sayhi('egon')
    t.start()    #start開始會運行run函數
    print('主線程')

 在一個進程字兒開啓多個線程與開啓多個進程的區別html

from threading import Thread             #線程模塊
from multiprocessing import Process         #進程模塊
import os
def work():
    print('hello')
if __name__ == '__main__':
    # t = Thread(target=work)    #開啓線程速度較快
    t = Process(target=work)     #從新申請內存空間,速度慢
    t.start()
    print('主線程:%s'%os.getpid())

  線程與進程的區別python

 線程中全部的數據共享ide

守護線程與守護進程的異同:函數

  主線程會等到全部非守護線程結束,才銷燬守護線程post

  主進程的代碼運行完畢,就會銷燬守護進程,而後等非守護進程運行完畢,主進程結束。this

 1 from threading import Thread
 2 import time
 3 def foo():
 4     print(123)
 5     time.sleep(2)
 6     print('end123')
 7 def bar():
 8     print(456)
 9     time.sleep(1)
10     print('end456')
11 if __name__ == '__main__':
12     t1 = Thread(target=foo)
13     t2 = Thread(target=bar)
14     t1.daemon = True
15     t1.start()
16     t2.start()
17     print('this is father')
守護進程與守護線程
相關文章
相關標籤/搜索