【问题标题】:Run a function in a seperate python thread在单独的 python 线程中运行一个函数
【发布时间】:2020-08-07 00:53:04
【问题描述】:

(Python 3.8.3)

我现在使用两个 python 线程,一个有一个 while True 循环

import threading
def threadOne():
    while True:
        do(thing)
    print('loop ended!')
t1=threading.Thread(threadOne)
t1.start()

另一个检查 ctrl+r 输入。收到后,我需要第二个线程告诉第一个线程从 while 循环中中断。有没有办法做到这一点?

请注意,我无法将循环更改为“while Break == False”,因为 do(thing) 等待用户输入,但我需要将其中断。

【问题讨论】:

    标签: python python-3.x multithreading


    【解决方案1】:

    推荐的方法是使用 threading.event(如果你也想在那个线程中休眠,你可以将它与 event.wait 结合起来,但是当你在等待用户事件时,可能不需要那个)。

    import threading
    
    e = threading.Event()
    def thread_one():
        while True:
            if e.is_set():
                break
            print("do something")
        print('loop ended!')
    
    t1=threading.Thread(target=thread_one)
    t1.start()
    # and in other thread:
    import time
    time.sleep(0.0001)  # just to show thread_one keeps printing
                        # do something for little bit and then it break
    e.set()
    

    编辑:要中断线程在等待用户输入时,您可以将 SIGINT 发送到该线程,它会引发 KeyboardInterrupt ,然后您可以处理它。 python(包括python3)的不幸限制是所有线程的信号都在主线程中处理,因此您需要在主线程中等待用户输入:

    import threading
    import sys
    import os
    import signal
    import time
    
    def thread_one():
        time.sleep(10)
        os.kill(os.getpid(), signal.SIGINT)
    
    t1=threading.Thread(target=thread_one)
    t1.start()
    
    while True:
        try:
            print("waiting: ")
            sys.stdin.readline()
        except KeyboardInterrupt:
            break
    print("loop ended")
    

    【讨论】:

    • 没错。如您所见,e 是一个全局变量,由所有线程共享。 thread_one 可以简单地检查变量的值,而不需要事件。例如。 withwhile go_ahead do stuffthread_two 设置 go_ahead = False 告诉它停止
    • 不,这不是我需要的。 do(something) 包含一个输入语句,我需要在用户输入之前中断它,而不是之后,好像用户必须在循环中断之前输入输入,while 循环会做其他事情。
    • 哦,我知道您需要在等待输入时中断它!然后你应该向那个线程发送一个信号来处理它。
    猜你喜欢
    • 2017-05-07
    • 2022-11-19
    • 2018-01-07
    • 2021-12-16
    • 2018-07-28
    • 2021-06-17
    • 2014-12-14
    • 1970-01-01
    • 2016-04-23
    相关资源
    最近更新 更多