我正在寻找一种使用 sys.exit() 终止线程的方法。
我有两个函数 add1()
和 subtract1()
,分别由每个线程 t1
和 t2
执行。我想在完成 add1()
后终止 t1
,并在完成 subtract1()
后终止 t2
。我可以看到 sys.exit() 可以完成这项工作。这样可以吗?
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() 的非标准使用(实际上并没有退出)而感到困惑。
class MyDescriptiveError(Exception):
pass
def my_function():
raise MyDescriptiveError()
关于python - 使用 sys.exit() 终止 python 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15770261/