[英]Terminate script with threads python
我有一些代碼:
red = "\033[1;31m"
green = "\033[1;32m"
yellow = "\033[1;33m"
blue = "\033[1;34m"
defaultcolor = "\033[0m"
class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
x=1
def timer(stopon):
timertime = 0
while True:
time.sleep(1)
timertime += 1
print timertime
if timertime == stopon:
killpro()
def killpro():
sys.exit()
threadsyy = []
threadsamount = 300
i = 1
while i <= threadsamount:
thread = watek()
threadsyy.append(thread)
i += 1
print(yellow + "Thread number" + defaultcolor + ": " + red + str(i) + yellow + " created." + '\n')
a = 0
for f in threadsyy:
f.start()
a += 1
#print "Thread work " + str(a)
timer(5)
而且我需要在5秒后終止密碼。 我試圖用sys.exit
和殺害使用過程psutil
。 有人知道如何終止嗎? 我正在嘗試:
class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()
和使用
watek.kill()
但它也不起作用。
這不會解決您的問題,但是如果有人從搜索引擎中尋找到實際上仍在運行中的結束線程,我將在此保留。
class worker(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self)
def run(self):
main_thread = None
for thread in threading.enumerate():
if thread.name == 'MainThread':
main_thread = thread
break
while main_thread and main_thread.isAlive():
#do_work()
print('Thread alive')
time.sleep(1)
# I'll keep some of the analogy from above here:
threads = []
thread = worker()
threads.append(thread)
for f in threads:
f.start()
time.sleep(5)
for f in threads:
print('Is thread alive:', f.isAlive())
程序將在大約5秒鍾后退出,如果線程仍然存在(它們將仍然存在) ,則在打印后立即退出,但是這些線程將查找主進程狀態,並在主線程死亡時終止。
這是一種創建線程的方法,該線程將在主程序運行時結束。
在實踐中,問題更大,您必須確保它們能很好地終止並自行清理。 還有f.join()
將等待線程終止,可以在這里找到很好的解釋: python線程中join()的用途是什么
還向線程發出了退出該線程的信號,對此也進行了詳盡的討論,這里有一個很好的例子: 如何在Python中停止循環線程?
這只是一個最小的示例(仍不完整,但可以正常工作) ,該示例顯示了如何創建在主程序執行時終止的線程的一般要點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.