首页 文章

Python线程,为什么我只能启动一次线程?

提问于
浏览
0

我在网络设备上有看门狗的简单脚本 . 脚本监视来自PING命令的响应 . 如果没有答案,则执行第二个线程并停止第一个线程 . 如果第二个线程完成,则恢复第一个线程(检查ping) . 如果没有答案,则显示以下消息:RuntimeError:线程只能启动一次

#!/usr/bin/python

    import os
    import time
    import sqlite3
    from ablib import Pin
    import threading

    led=Pin('W9','OUTPUT')

    class threadout1(threading.Thread):
      def run(self):
        while True:
            conn = sqlite3.connect('database/database.db')
            cur = conn.cursor()
            cur.execute("SELECT * FROM watchdog")
            rows_output = cur.fetchall()
            time.sleep(1)

            if rows_output[0][1] == "ping":
                response = os.system("ping -c 1 " + rows_output[0][2])
                if response != 0:
                    print "bad"
                    rest.start()
                    rest.join()     

    class restart(threading.Thread):
      def run(self):
        led.on()
        time.sleep(15)
        led.off()

    thr = threadout1()
    rest = restart()
    thr.start()

1 回答

  • 3

    您可以在每次需要时创建 restart 线程

    if response != 0:
    print "bad"
    restart_thread = restart()
    restart_thread.start()
    restart_thread.join()
    

    或使用Events

    class restart_thread(threading.Thread):
      def __init__(self, evt):
        self.evt = evt
    
      def run(self):
        self.evt.wait()
        # do stuff
        self.evt.clear()
    
    class threadout(threading.Thread):
      def __init__(self, evt):
        self.evt = evt
    
      def run(self):
        if #other thread needs to run once
          self.evt.set()
    
    evt = threading.Event()
    restart_thread = restart(evt)
    restart_thread.start()
    pinging_thread = threadout(evt)
    pinging_thread.start()
    

    要使 pinging_thread 等待 restart_thread 完成,您可以使用另一个事件 .

相关问题