python - 使用 sys.exit() 终止 python 线程

标签 python multithreading exit terminate

我正在寻找一种使用 sys.exit() 终止线程的方法。 我有两个函数 add1()subtract1(),分别由每个线程 t1t2 执行。我想在完成 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/

相关文章:

c++ - Google 测试中的 EXPECT_NO_DEATH()

python - 在Python中执行2D矩阵过滤的有效方法是什么?

python - 使用全局标志进行 python RegExp 编译

python - PyQt5 - 显示虚拟键盘

python - 未处理的异常在 Windows 上中止 python 进程,但在 OS X 上则不然

c - 如何等待所有子进程终止并获取每个退出状态

python - 什么是周期?关于 python

java - 如何停止或退出 "Runnable"

windows - 为什么它像没有线程一样运行?

python - 有没有办法防止从 sys.exit() 引发的 SystemExit 异常被捕获?