有关守护程序和非守护程序线程的问题

时间:2020-05-24 23:36:59

标签: python multithreading

我正在尝试学习Python中的线程。我知道当App Main Threat退出时,守护线程也会终止,但是任何非守护线程都将执行到最后。因此,基于此,有谁能告诉我为什么即使在线程D(非守护线程)仍在执行时,此代码也会停止?!

它在Thonny上的输出是:

Starting of thread : Thread A

Starting of thread : Thread B

Finishing of thread : Thread B

Finishing of thread : Thread A

Starting of thread : Thread C

Starting of thread : Thread D

我的代码:

import threading
import time


def a():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(10)
  print('Finishing of thread :', threading.currentThread().name)


def b():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(5)
  print('Finishing of thread :', threading.currentThread().name)


a = threading.Thread(name = "Thread A", target = a)
b = threading.Thread(name = "Thread B", target = b)
a.start()
b.start()


time.sleep(15)  # Just a pause between Threads A,B and C,D.


def c():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(10)
  print('Finishing of thread :', threading.currentThread().name)


def d():
  print('Starting of thread :', threading.currentThread().name)
  time.sleep(5)
  print('Finishing of thread :', threading.currentThread().name)


c = threading.Thread(name = "Thread C", target = c, daemon = True)
d = threading.Thread(name = "Thread D", target = d)
c.start()
d.start()

exit()

0 个答案:

没有答案
相关问题