【问题标题】:Terminate python threads using sys.exit()使用 sys.exit() 终止 python 线程
【发布时间】:2013-04-02 17:19:04
【问题描述】:

我正在寻找一种使用 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 函数关闭整个解释器。您可能应该使用其他东西。
  • 你不应该寻找杀死线程的方法。当涉及到 I/O 时(而且不仅如此),它可能会导致严重的问题。相反,您应该通知您的线程您希望它完成它正在做的任何事情并退出。

标签: python multithreading exit terminate


【解决方案1】:

sys.exit() 真的只会引发 SystemExit 异常,并且只有在主线程中调用它才会退出程序。您的解决方案“有效”,因为您的线程没有捕获 SystemExit 异常,因此它终止了。我建议您坚持使用类似的机制,但使用您自己创建的异常,这样其他人就不会被 sys.exit() 的非标准使用(并没有真正退出)所迷惑。

class MyDescriptiveError(Exception):
    pass

def my_function():
    raise MyDescriptiveError()

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多