Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用sys.exit()终止python线程_Python_Multithreading_Exit_Terminate - Fatal编程技术网

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

使用sys.exit()终止python线程,python,multithreading,exit,terminate,Python,Multithreading,Exit,Terminate,我正在寻找一种使用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 tot

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


sys.exit
功能关闭整个解释器。您可能应该使用其他方法。您不应该寻找杀死线程的方法。当涉及I/O时,它可能会导致严重的问题(不仅如此)。相反,您应该通知您的线程您希望它完成它正在做的任何事情并退出。
class MyDescriptiveError(Exception):
    pass

def my_function():
    raise MyDescriptiveError()