1

I am looking for a way to terminate a thread by using sys.exit(). I have two functions add1() and subtract1(), which are executed by each thread t1 and t2 respectively. I want to terminate t1 after finishing add1() and t2 after finishing subtract1(). I could see that sys.exit() do that work. Is it ok to do in such way?

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()
2
  • 1
    The sys.exit function shuts down the whole interpreter. You should probably use something else. Commented Apr 2, 2013 at 17:29
  • You should not look for a way to kill threads. It might lead to serious issues when I/O is involved (and not only). Instead you should notify your thread that you want it to finish whatever it's doing and quit. Commented Apr 2, 2013 at 17:44

1 Answer 1

2

sys.exit() really only raises the SystemExit exception and it only exits the program if it is called in the main thread. Your solution "works" because your thread doesn't catch the SystemExit exception and so it terminates. I'd suggest you stick with a similar mechanism but use an exception you create yourself so that others aren't confused by a non-standard use of sys.exit() (which doesn't really exit).

class MyDescriptiveError(Exception):
    pass

def my_function():
    raise MyDescriptiveError()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.