1. 守護(hù)線程
- 使用setDaemon(True)把所有的子線程都變成了主線程的守護(hù)線程,因此當(dāng)主進(jìn)程結(jié)束后,子線程也會隨之結(jié)束。所以當(dāng)主線程結(jié)束后务冕,整個程序就退出了。
- 把子進(jìn)程設(shè)置為守護(hù)線程幻赚,必須在start()之前設(shè)置禀忆。
- 為了讓守護(hù)線程執(zhí)行結(jié)束之后,主線程再結(jié)束落恼,我們可以使用join方法箩退,讓主線程等待子線程執(zhí)行
- join()在start()之后。
#!/usr/bin/env python
# coding:utf-8
import threading
import time
def run(n):
print(f'task {n}')
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
print('0s')
time.sleep(1)
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=('t1',))
t1.setDaemon(True) # 把子進(jìn)程設(shè)置為守護(hù)線程领跛,必須在start()之前設(shè)置
t1.start()
t1.join() # 設(shè)置主線程等待子線程結(jié)束
print('main thread end.')
2. 多線程共享全局變量
- 線程是進(jìn)程的執(zhí)行單元乏德,進(jìn)程是系統(tǒng)分配資源的最小單位撤奸,所以在同一個進(jìn)程中的多線程是共享資源的吠昭。
#!/usr/bin/env python
# coding:utf-8
import threading
import time
global_num = 100
def work1():
global global_num
for i in range(3):
global_num += 1
print(f'in work1 global_num is :{global_num}')
def work2():
global global_num
print(f'in work2 global_num is {global_num}')
if __name__ == '__main__':
t1 = threading.Thread(target=work1)
t1.start()
time.sleep(1)
t2 = threading.Thread(target=work2)
t2.start()
# output:
in work1 global_num is :103
in work2 global_num is 103