Python3 threading.Timer线程的命名有问题吗?

时间:2020-04-27 20:14:45

标签: python-3.x multithreading timer pygame

我正在Python3中使用threading.Timer对象在一个非常简单的pygame全屏窗口中触发图像的切换(想想数码相框的图片幻灯片)。

最下面的代码不是独立的功能,而只是一个说明。创建并启动计时器线程,完成后将布尔值self.signal_switch_image设置为True,这将触发图像切换。由于线程无法重新启动,因此每次都必须创建一个新线程,因此在进行新的分配时,旧线程将被垃圾回收(至少我认为是)。就像魅力一样。

仅检查未分配的旧线程是否确实被破坏,我打印了threading.enumerate()以确保不创建一百万个新线程。从理论上讲,该脚本要运行很长时间(一天或更长时间)。您可以在下面看到的输出:

[<_MainThread(MainThread, started 4148)>, <Timer(Thread-1, started 5300)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-2, started 11224)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-3, started 9116)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-4, started 4724)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-5, started 7856)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-6, started 6728)>]
[<_MainThread(MainThread, started 4148)>, <Timer(Thread-7, started 13512)>]

现在是我的问题,我可以肯定这是一个愚蠢的问题,但是无论如何我还是想问一下,因为我什至不知道要在Google博士中搜索什么。

您可以看到每个新线程在名称末尾都有下一个顺序整数。我是否需要担心Thread标题末尾的数字太大,例如螺纹-9123475981234750182374018243761087235081237?在作为业余程序员的那段时间,我遇到了许多奇怪的错误,如果这将成为一个问题,那将是调试的噩梦,所以我宁愿现在问,而我却注意到了。

非常感谢您抽出宝贵的时间来忍受无知的;-)

在这些陌生的时代照顾好自己...

def run(self):
    size = (0, 0)
    screen = pygame.display.set_mode(size, FULLSCREEN)

    running = True

    while running:
        if self.time2switch:
            # Changes the image
            self.change_image()

            # Creates new Timer thread
            self.time2switch = False
            timer = th.Timer(self.time_delay, self.signal_switch_image)
            timer.start()
            print(th.enumerate())

        self.img = pygame.image.load(self.imgpath)

        screen.fill(BLACK)
        screen.blit(self.img, centre_coord)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

0 个答案:

没有答案