【问题标题】:Causing a thread to stop while stuck within a while loop?导致线程卡在while循环中时停止?
【发布时间】:2017-04-03 15:26:48
【问题描述】:

当线程卡在while循环中时是否可以过早停止线程?下面是我的示例代码,它运行正常,因为每次调用loop_thread 时,它都会检查是否设置了threading.Event() 标志。当尝试为处理信息的时间比每秒长得多的文件运行代码时,无法阻止整个函数继续执行直到下一次迭代。例如,如果我运行dld_img_thread,大约需要 5 分钟才能完成它的执行并重新检查 while 循环以查看是否应该继续。我想要发生的是在不到 5 分钟(例如 1 分钟)的时间内杀死 dld_img_thread。我不在乎数据是否丢失,只是线程在函数完成执行之前停止。谢谢

import threading, time, pythoncom, read_mt0
import powerfail_debugport_reader as pf_dbg_rdr
import powerfail_firmware_downloader as pf_fwdld


def loop_thread(thread_name, thread_event):
    loopCnt = 0
    print "\nstarting {}".format(thread_name)
    print "is {0} alive? {1}\n".format(thread_name, L00P_thread.is_alive())
    while not thread_event.is_set():
        print("value of loopCnt = {}".format(loopCnt))
        loopCnt += 1
        time.sleep(1)
    print('stopping {}\n'.format(thread_name))

def image_dld(thread_name, thread_event):
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
    print "\nstarting {}".format(thread_name)
    print "is {0} alive? {1}\n".format(thread_name, dld_img_thread.is_alive())
    while not thread_event.is_set():
        pf_fwdld.power_fail_test()
    print('stopping {}'.format(thread_name))

def debug_port_thread(thread_name, thread_event):
    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
    print "\nstarting {}".format(thread_name)
    print "is {0} alive? {1}\n".format(thread_name, debug_thread.is_alive())
    pf_dbg_rdr.debug_port_reader()
    print('\nstopping {}'.format(thread_name))

def main():
    global L00P_thread, debug_thread
    pf_dbg_rdr.samurai_event = threading.Event()

    L00P_thread = threading.Thread(target=loop_thread, \
        args=('L00P_thread', pf_dbg_rdr.samurai_event))

    dld_img_thread = threading.Thread(target=image_dld, \
        args=('image_download', pf_dbg_rdr.samurai_event))

    debug_thread = threading.Thread(target=debug_port_thread, \
        args=('debug_port_reader', pf_dbg_rdr.samurai_event))

    L00P_thread.start()
    dld_img_thread.start()
    debug_thread.start()
    debug_thread.join()

if __name__ == '__main__':
    main()
    print('processes stopped')
    print "Exiting Main Thread"

【问题讨论】:

    标签: python multithreading python-2.7 loops


    【解决方案1】:

    在您的 while 条件中使用第二个变量,一旦达到超时,您就可以更改它。

    例如:

    shouldRun = True
    while not thread_event.is_set() and shouldRun:
        print("value of loopCnt = {}".format(loopCnt))
        loopCnt += 1
        time.sleep(1)
        if loopCnt > 60: shouldRun = False
    

    将在 60 次迭代后停止(大约 60 秒,因为您每次迭代睡眠 1 秒)。

    【讨论】:

    • 这对于循环线程工作正常,但对于解释的另一个线程,这个过程将不起作用。我在一个外部函数中设置了一个标志,它应该停止另一个线程,但它只有在整个函数完成执行后才会起作用。
    • 抱歉,没发现。一次尝试做太多事情是我的错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多