Carlos Barreiro Mata
Carlos Barreiro Mata

Reputation: 37

Kill Python Thread

I'm working with a robot using python. I'm using multi-threading (two threads in this case). And I want to stop thread A when thread B receives an event.

main:

tA = threading.Thread(target=runThreadA)
tA.setDaemon(True)

tB = threading.Thread(target=runThreadB)
tB.setDaemon(True)

tA.start()
tB.start()

Thread A:

def runThreadA():
    print "Estado1"
    time.sleep(5)
    print "Finalizo Estado1"
    return 'out1'

Thread B:

def runThreadB():
    print "Estado2"
    time.sleep(8)
    print "Finalizo Estado2"
    return 'a1'

WE want to kill the thread B when the thread A has finished, so the thread B don't be waiting 3 seconds more.

Thank you.

Upvotes: 0

Views: 217

Answers (1)

宏杰李
宏杰李

Reputation: 12168

Never try to kill a thread from something external to that thread. You never know if that thread is holding a lock. Python doesn’t provide a direct mechanism for kill threads externally; however, you can do it using ctypes, but that is a recipe for a deadlock.

This quote is from Raymond Hettinger, there is a speech about this.

Upvotes: 1

Related Questions