Abort a specific Thread

Asked

Viewed 339 times

1

How do I interrupt a specific thread? for example:

from _thread import *
from time import sleep
result = 0

def soma(nome, numero, delay):
global result
while True:
    result += numero
    print('{}: {} '.format(nome, result))
    sleep(delay)

start_new_thread(soma,('Th 1', 1, 3))
start_new_thread(soma,('Th 2', 1, 1))

while True:
    pass

How would I, for example, interrupt Th2 and let Th1 run? or vice versa

  • When you say interrupt refers to finishing your execução or deletá-la?

  • Delete it, but either finish its execution, whatever rsrs, as long as it is no longer active...

1 answer

1

Unfortunately, unable to interrupt threads. The only way a thread ends is to let her code run to the end. What you can do, if your thread has a loop, is establish a communication channel with the thread, using a mechanism like Queues, and make your thread check that channel within the loop. Then your main program can use the channel to send a message to the thread, which, when checking the channel, will see that it should stop the loop and close.

In other words, you have to write code to ask the thread to commit suicide, and if she’s listening, she’ll do it.

I suggest avoiding the use of threads, in python there are almost no advantages in using threads because of GIL. Use asynchronous programming, so you can control the timing of the context change and therefore make parallel structures more cancellable. See for example this article (in English):

https://vorpus.org/blog/timeouts-and-cancellation-for-humans/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.