我正在为我的课程构建多线程教程。我下面有一个简单的代码,它初始化3个线程。线程1,2,3。
线程1:等待4秒的简单计时器
线程2:等待2秒的简单计时器
线程3:简单的计时器,它等待6秒,但是是守护程序。
主程序在第三个线程结束之前完成。因为第三个线程是守护进程,所以我认为它将被杀死。因此,我想知道我的代码或jupyter-notebook出了什么问题。这是我的代码。
import threading
import logging
import time
def threadLauncher1(name, delay):
logging.info("Thread %s \t : Starting" %name)
time.sleep(delay)
logging.info("Thread %s \t : Finishing" %name)
class threadLauncher2(threading.Thread):
def __init__(self, name, delay):
super().__init__()
self.name = name
self.delay = delay
def run(self):
logging.info("Thread %s \t : Starting" % self.name)
time.sleep(self.delay)
logging.info("Thread %s \t : Finishing" % self.name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
threadLauncherFunction1 = threading.Thread(target=threadLauncher1, args=("Timer 1", 4,))
threadLauncherFunction1.start()
threadLauncherFunction2 = threadLauncher2("Timer 2", 2)
threadLauncherFunction2.start()
threadLauncherFunction3 = threadLauncher2("Timer 3", 6)
threadLauncherFunction3.setDaemon(True)
threadLauncherFunction3.start()
logging.info("Daemon setting is %s on %s" % (str(threadLauncherFunction3.isDaemon()), threadLauncherFunction3.name))
threadLauncherFunction1.join()
logging.info("Waited until Timer 1 had finished")
logging.info("Timer3 should not be able to finish, since it is a daemon Thread")
我尝试用更明确的功能替换第3个线程。
class threadLauncher3(threading.Thread):
def __init__(self, name, delay):
super().__init__()
self.name = name
self.delay = delay
def run(self):
while True:
logging.info('Thread %s running.' %self.name)
time.sleep(self.delay)
如先前结果所示,输出为:
13:19:37: Thread Timer 1 : Starting
13:19:37: Thread Timer 2 : Starting
13:19:37: Thread Timer 3 running.
13:19:37: Daemon setting is True on Timer 3
13:19:38: Thread Timer 3 running.
13:19:39: Thread Timer 2 : Finishing
13:19:39: Thread Timer 3 running.
13:19:40: Thread Timer 3 running.
13:19:41: Thread Timer 1 : Finishing
13:19:41: Waited until Timer 1 had finished
13:19:41: Timer3 should not be able to finish, since it is a daemon Thread
13:19:41: Thread Timer 3 running.
13:19:42: Thread Timer 3 running.
13:19:43: Thread Timer 3 running.
To infinity
这两个代码在我的计算机的解释器上正常工作。
答案 0 :(得分:0)
问题在于正常退出处理是当所有非守护程序线程都消失时守护程序线程终止时,但是当jupyter笔记本中的单元完成执行时没有完成“正常”退出处理。您将必须更改run
方法,以便在设置“暂停”条件时最终返回该方法。例如,您可以添加一个do_halt
方法,该方法设置一个将由run
检查并随后执行join
的属性:
class threadLauncher3(threading.Thread):
def __init__(self, name, delay):
super().__init__()
self.name = name
self.delay = delay
self.halt = False
def run(self):
while not self.halt:
logging.info('Thread %s running.' %self.name)
time.sleep(self.delay)
def do_halt(self):
self.halt = True
self.join()
# code omitted
threadLauncherFunction3.do_halt()