我正在寻找一种使用 sys.exit() 来终止线程的方法。我有两个函数add1()
和subtract1()
,它们分别由每个线程t1
和执行t2
。我想t1
在完成后add1()
和t2
完成后终止subtract1()
。我可以看到这样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()