[英]Why can I launch a thread (with the python threading module) only once?
我在网络设备上有简单的看门狗脚本。 脚本监控来自 PING 命令的响应。 如果没有答案,则执行第二个线程并停止第一个线程。 如果第二个线程完成,则恢复第一个线程(检查 ping)。 如果没有答案,则会出现以下消息:
运行时错误:线程只能启动一次
这是我的代码:
#!/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()
您可以在每次需要时创建restart
线程
if response != 0:
print "bad"
restart_thread = restart()
restart_thread.start()
restart_thread.join()
或使用 事件
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
到结束,你可以使用其他事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.