-2

I am implementing a Flask application and I'm calling a function A, based on a request. Inside the function A, there is another function called B and it is called. But, I don't need to wait until the end of the execution of function B to return the output from function A. I have done it with the following code implementation.

from threading import Thread

def functionA():
    result = doSomething1()
    Thread(target=functionB).start()
    return result

def functionB():
    # Do something after the execution of doSomething1()

Here, I am starting a new thread and do what I need to do but, I do not terminate the newly started thread. Do I need to terminate that thread by myself? If so, what is the best way to do that?

Ayesh Weerasinghe
  • 580
  • 2
  • 7
  • 19
  • 1
    why you need to terminate after starting it. – pavan Oct 28 '19 at 09:57
  • If you really want the thread to terminate use concurrent futures it has options for both sync and async – pavan Oct 28 '19 at 10:55
  • Why are you using a thread in the first place? What does it do? Why do you need to terminate it? – Ulrich Eckhardt Oct 28 '19 at 12:11
  • To run the functionB, doSomething1 should be executed first. functionB takes some time to process while I don't need to wait for it to return the 'result' of functionA. That's why I used a thread. @UlrichEckhardt – Ayesh Weerasinghe Oct 29 '19 at 05:19
  • @pavan At the end of the execution of functionB, I don't have anything to do with the started thread more. That's why I thought to terminate the thread. If the thread will terminate on its own as said in below answer, it is ok. Correct me if I'm wrong. – Ayesh Weerasinghe Oct 29 '19 at 05:22

1 Answers1

0

A thread will terminate on its own. To see if it is alive you can use thread.is_Alive()

If you must force termination of a thread, use thread.join() would be the closes option, as this blocks the calling thread until the thread in question has finished.

Also refer to the docs for more info on the Threading functions

https://docs.python.org/3/library/threading.html

Jason Chia
  • 1,144
  • 1
  • 5
  • 18