我有一些密码:
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秒后终止scipt。我尝试使用sys.exit
并使用psutil
终止进程。有人知道怎么终止吗?我正在尝试:
class watek(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._kill = threading.Event()
使用
watek.kill()
但也不管用。你知道吗
这不会解决你的问题,但我会把这个留在这里,以防有人从搜索引擎来寻找结束线程很好的线程实际上仍然活着。你知道吗
程序将在~5秒后退出,如果线程仍然活着,则在打印之后立即退出(它们将是),但是这些线程将查找主进程状态并在主线程死亡时终止。你知道吗
这是创建线程的一种方法,该线程将在主程序运行时结束。
在实践中问题更大,你必须确保它们很好地终止,并自己清理它们。还有
f.join()
等待线程终止,这里可以找到一个很好的解释:what is the use of join() in python threading还有一个信号告诉线程是时候退出了,这也已经被彻底讨论过了,这里有一个很好的例子:How to stop a looping thread in Python?
这只是一个很小的示例(仍然不完整,但是可以工作),它展示了如何创建在主程序执行时终止的线程的一般要点。你知道吗
相关问题 更多 >
编程相关推荐