0
How to stop one, or all threads in python by ID (example)
I’m developing a program that should run some loops looking for information in real time. However, when any of them find something the thread that runs it should be finished, or even all threads.
Below is an example of the code:
def log(palavras):
while True:
... # processos diversos aqui
if palavra == 'Gato':
# parar thread relacionada a esse loop
# OU parar todas as threads
break
... # Continua o processo do script
def iniciaThreads():
animais = ('Gato', 'Cachorro', 'Papagaio') # Exemplo com 3 items, mas podem ser vários
for pet in animais:
t = Thread(target=log, args=[pet])
procAnimais.append(t)
# Inicia todas as Threads
for x in procAnimais:
x.start()
iniciaThreads()
I don’t know if it exists, but I thought of some way to send the thread ID to the function that loops and closes it there via parameter:
t = Thread(target=log, args=[pet, id_thread])
And in the loop when it reaches some condition perform:
...
id_thread.stop()
break
Of a read in 'threading.Thread.Join()'.
– Augusto Vasques
@Augustovasqueseu had already read but did not know how to use it. So did several other examples that did not work within a loop. But thanks for sharing.
– Maurício Morhy
I like to do the following. I create a class using the Singleton project pattern. Instead of using
while True
, usewhile var_no_singleton
, in a certain condition I update the variable and ready the thread that had thatvar_no_singleton
will exit the loop. If there are several, yourvar_no_singleton
would be a dictionary...– Paulo Marques