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