如何在 Python (2.7.12)(线程?)

How do I do multiple things at once in Python (2.7.12) (Threading?)

我正在研究如何加载一个长 python 程序并同时制作加载动画 运行。我环顾四周,找到了线程,但一直无法找到如何使用线程来执行此操作。

编辑:我的代码https://gyazo.com/adb1f0a77d58ba89c9b133972bc17d03

你的编码在这台学校计算机上被阻止,所以我没有看到提供的编码,但我仍然可以提供帮助。您可以使用内置的 Python 线程模块来执行此操作。

首先,您需要将加载动画放在一个函数中。将此动画放在一个 while 循环中,该循环在变量为 True 时终止,让我们使用 loadingfinished

def loading_animation():
    global loadingfinished # may or may not be needed
    while not loadingfinished:
        #insert code here

创建此函数后,您会将 loadingfinished 设置为零。

现在,在确保模块 "thread" 已导入后,您将输入

thread.start_new(loading_animation, ())

这 loading_animation 作为一个新线程启动,没有参数。在此之后,您将只有正常的代码,即您需要加载的内容。

完成加载代码后,只需将 loadingfinished 设置为 True!你的代码应该是这样的:

import thread

def loading_animation():
    global loadingfinished # may or may not be needed
    while not loadingfinished:
        #insert animation code here

loadingfinished = False
thread.start_new(loading_animation, ())

#insert loading code here

loadingfinished = True
#This by itself causes the separate thread to terminate.

#You may want to put a delay of a tenth of a second or so here,
#to make extra sure the other thread is terminated before you continue.

多线程是一门非常值得学习的东西,尤其是在 Python 中,因为它是一种缓慢的语言。我通常喜欢将我的 blitting 和计算分成不同的线程。这几乎可以使您的程序性能翻倍!

您可以在此处了解有关线程模块的更多信息: https://docs.python.org/2/library/thread.html#module-thread

我无法测试这段代码,所以如果有任何错误,请在下面的评论中告诉我。