T
T
Ternick2019-10-04 23:47:24
Python
Ternick, 2019-10-04 23:47:24

How to terminate an application if multiple threads are running?

There is a simple script that downloads some files in an endless loop in several threads.
It takes the time for which it must download what it has time to complete.
I usually end the application with a simple exit() or sys.exit(), but in this case, after these functions are executed, the script continues to 'live' at the expense of threads.
How would you end all threads at once?
{I looked at different Googles and it says to make a variable indicating whether the function works or not, but wait until the loop ends and the while check starts, I don’t want to wait}
Apparently I didn’t explain well:

from threading import Thread
from time import sleep

global work
work = True

def thread(my_func):
  def wrapper(*args, **kwargs):
    my_thread = Thread(target=my_func, args=args, kwargs=kwargs)
    my_thread.start()
  return wrapper

@thread
def work():
    while work:#Суть в том что пока сон не закончится проверка не будет выполнена, а иногда времени нет на то что бы ожидать пока всё это завершится
        sleep(10)# имитация бурной деятельности

def main():
    for i in range(0, 5):
        work()
    sleep(15)
    global work
    work = False

if __name__ == '__main__':
  main()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Temnikov, 2019-10-05
@Ternick

Typically, a Python application does not terminate while at least one of its threads is running. But there are special threads
that do not interfere with the closing of the program and stop with it. Such threads are called
"daemons"

thread = Thread(target=task(*args,**kwargs), daemon=True)
thread.setDaemon(True/False)
thread.isDaemon()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question