Python threading, why can i launch thread only once?
在具有简单的脚本的看门狗ASON网络的装置。脚本从命令ping应答的监视器。如果有第二次,然后回答executes第一线程的线程停止冰。如果第二线程的线程完成然后冰一冰resumed(检查平)。如果答案是有没有出现以下消息:runtimeerror:螺纹可以只读一次的开始
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #!/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 2 3 4 5 | if response != 0: print"bad" restart_thread = restart() restart_thread.start() restart_thread.join() |
或使用事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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() |
要使