Interrupt a specific Thread

1

How do I stop 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, stop the Th2 and leave Th1 running? or vice versa

    
asked by anonymous 14.10.2018 / 17:56

1 answer

0

Unfortunately, can not pause threads . The only way for a thread to finish is to let the code run through to the end. What you can do, if your thread has a loop, is to establish a communication channel with the thread, using a mechanism like Queue s, and have 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 it is listening, it will.

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 context switching and therefore make parallel structures more cancelable. See for example this article:

link

    
15.10.2018 / 03:01