繁体   English   中英

python 中的线程,没有错误,但程序似乎不起作用

[英]Threading in python, no errors but program doesn't seem to work

我正在为我的树莓派开发一个程序。 目前我只是想让程序打印“黄色 LED 亮”或“红色 LED 亮”。 我是线程新手,但不是 python。 我目前写了一些代码,但是我不知道为什么当我运行它时,什么都没有发生,并且程序永远不会终止。 如果有人有任何想法,他们将不胜感激。 我已经发布了下面的代码。 提前致谢。

from threading import Thread
import random
import time

def blinking_LED(n,t):
    i = 10
    for x in range (n,i):
        if (x % 2) == 0:
            color = "yellow"
            n += 1
        else:
            color = "red"
            n += 1
    # output result
        if (color == "yellow"):
            print ("Yellow LED on")
            time.sleep(2)
        else:
            print ("Red LED on")
            time.sleep(2)
    #exit function, terminate program
    s.quit()

if __name__ == "__main__":

    # value to pass into the functions
    v = 1

    # create threads
    t1 = Thread(target=blinking_LED, args=(v,1))

    # Start threads
    t1.start()

    #tell main thread to stay alive until both threads are done
    t1.join()
from threading import Thread
import time


def blinking_LED(n):
    for x in range(n):
        if (x % 2) == 0:
            print("Yellow LED on")
        else:
            print("Red LED on")
        time.sleep(1)


if __name__ == "__main__":
    t1 = Thread(target=blinking_LED, args=(10,))
    t1.start()

    # Tell main thread to stay alive until both threads are done
    t1.join()

您不必调用 s.quit(),不管它是什么,当 function 返回时,线程将终止。

我不确定您的问题出在哪里,坦率地说,您的代码有点难以阅读。 看上面的例子,它每秒打印“LED on”,交替 colors,并在 10 次迭代后终止。

我想通了,首先我需要将“s.quit()”更改为“exit()”。 其次,我不知道为什么,但我将所有代码复制并粘贴到一个新文件中并尝试运行它,一切正常。 我不确定问题是什么,但由于某种原因它现在运行。 我感谢所有的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM