使用sys.exit()终止python线程 [英] Terminate python threads using sys.exit()
问题描述
我正在寻找一种使用sys.exit()终止线程的方法.
我有两个函数add1()
和subtract1()
,分别由每个线程t1
和t2
执行.我想在完成add1()
之后终止t1
,并在完成subtract1()
之后终止t2
.我可以看到sys.exit()
可以完成这项工作.这样可以行吗?
I am looking for a way to terminate a thread by using sys.exit().
I have two functions add1()
and subtract1()
, which are executed by each thread t1
and t2
respectively. I want to terminate t1
after finishing add1()
and t2
after finishing subtract1()
. I could see that sys.exit()
do that work. Is it ok to do in such way?
import time, threading,sys
functionLock = threading.Lock()
total = 0;
def myfunction(caller,num):
global total, functionLock
functionLock.acquire()
if caller=='add1':
total+=num
print"1. addition finish with Total:"+str(total)
time.sleep(2)
total+=num
print"2. addition finish with Total:"+str(total)
else:
time.sleep(1)
total-=num
print"\nSubtraction finish with Total:"+str(total)
functionLock.release()
def add1():
print '\n START add'
myfunction('add1',10)
print '\n END add'
sys.exit(0)
print '\n END add1'
def subtract1():
print '\n START Sub'
myfunction('sub1',100)
print '\n END Sub'
sys.exit(0)
print '\n END Sub1'
def main():
t1 = threading.Thread(target=add1)
t2 = threading.Thread(target=subtract1)
t1.start()
t2.start()
while 1:
print "running"
time.sleep(1)
#sys.exit(0)
if __name__ == "__main__":
main()
推荐答案
sys.exit( )实际上只会引发SystemExit异常,并且只有在主线程中被调用时才会退出程序.您的解决方案有效"是因为您的线程没有捕获SystemExit异常,因此它终止了.我建议您坚持使用类似的机制,但是使用您自己创建的异常,以免其他人被sys.exit()的非标准用法所迷惑(不会真正退出).
sys.exit() really only raises the SystemExit exception and it only exits the program if it is called in the main thread. Your solution "works" because your thread doesn't catch the SystemExit exception and so it terminates. I'd suggest you stick with a similar mechanism but use an exception you create yourself so that others aren't confused by a non-standard use of sys.exit() (which doesn't really exit).
class MyDescriptiveError(Exception):
pass
def my_function():
raise MyDescriptiveError()
这篇关于使用sys.exit()终止python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!