[英]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.