0

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.

  • 3
    you'll have to show us a part of your code, ideal would be a [mcve] with the missing parts highlighted. – Jean-François Fabre Jan 13 '17 at 09:37
  • 2
    Possible duplicate of [Is there any way to kill a Thread in Python?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) – ppasler Jan 13 '17 at 09:38

1 Answers1

1

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.

宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • 1
    +1 but I think that you can interrupt the thread without ctypes using inspect and messing with Python stack frames directly. I have no time to test the idea, but I think it should be possible. Of course I agree that this shouldn't be done except in extreme situations, and, well, managing GIL would be problematic part here. Perhaps garbage collecting too. – Dalen Jan 13 '17 at 11:36