线程目标函数仅运行一个循环

我试图在后台运行一个函数,直到在main函数中完成一些工作,然后完成线程。我已经在单独的类中实现了线程逻辑,而在另一个文件中实现了主线程。但是每次我运行它时,目标函数似乎只运行一次然后等待

这是主要功能

from ThreadRipper import *

thread_obj=ThreadRipper()
thread_obj.start_thread()
squish.snooze(10)
print("Main Continuing")
thread_obj.stop_thread()

实现的类如下

class ThreadRipper():

def __init__(self):
    lib_path="iCOMClient.dll"
    self.vx = IcomVx(lib_path)
    config = ConfigParser.SafeConfigParser(allow_no_value=True)
    config.readfp(open("vx_logger_config.cfg"))
    self.vx.connect(config.get("icom","ip"),timeout_millis = 30000)
    self.t = threading.Thread(target=self.task_to_do,args=(self.vx,))

def stop_thread(self):
    self.t.do_run=False
    self.t.join()

def start_thread(self):
    self.t.start()


def task_to_do(self,arg):
    current_thread=threading.currentThread()
    while getattr(current_thread,"do_run",True):
        with open("vx.txt",'a') as f:
            f.write(str(arg.get_next_message()._rawmsg)+"\n")
        time.sleep(1)
        print("Stopping")
        arg.disconnect()

运行此命令时,我创建了vx文件,但只有一个条目,我希望它可以连续写入,直到while循环退出。我对线程很陌生,可能对它的理解不正确。请指教

谢谢

fangshijie66 回答:线程目标函数仅运行一个循环

原因可能是因为

    print("Stopping")
    arg.disconnect()

都在while循环中。断开连接后,arg似乎不再产生任何消息。

(当然,除非您在问题中的代码不是您真正拥有的代码,但是在这种情况下,您肯定会编辑问题以使其匹配。)

本文链接:https://www.f2er.com/3117738.html

大家都在问