1

Consider the following Python function:

def make_request(arg1, arg2):
    make http request

I want to be able to create 5 threads that all call the make_request() function, however, I want it to be the case that as soon as one thread finishes another identical thread (making the same call to the make_request() function) starts. It seems that python does not actually support the 'restarting' of threads, so I thought to make it so that the make_request() never terminates by means of a while True: loop like so:

def make_request(arg1, arg2):
    while True:
        make http request

However, this does not seem like best practice and I am not sure if this approach may have unintended consequences.

knowledge_seeker
  • 811
  • 1
  • 8
  • 18
  • Is just a simple for loop launching the thread and then waiting for it with a join not sufficient? I.e. `for _ in range(5): thread = threading.Thread(target=make_request); thread.start(); thread.join()` – alkasm Mar 09 '21 at 18:07
  • You can use a pool of threads of a fixed size. These can be fed from an iterable containing work items. As soon as the first thread finishes it will be given the next item. – quamrana Mar 09 '21 at 18:08
  • 2
    I don't see anything wrong with the while loop. Remember the KISS principle – flakes Mar 09 '21 at 18:10
  • 2
    "this does not seem like best practice" why not? as long as you mark the thread as a daemon, and don't hold any resources that aren't properly cleaned up on exit, this looks fine to me. I use `while True` loops all the time. I would even argue for daemon threads, it's the canonical way to do it. – Aaron Mar 09 '21 at 18:12
  • @alkasm no, because I don't want them to be joined, because I don't expect it to terminate. – knowledge_seeker Mar 09 '21 at 18:12
  • @user13834264 Ah I understood your post to mean: you have 5 threads, and you want them to run one after the other, not that you have 5 different functions that you want to loop indefinitely. In that case, a `while True` is fine and common. If you need cancellation ability, just pass a `threading.Event` to the thread and loop `while not event.is_set()`, and someone external could flag `event.set()` to flag all threads to stop. – alkasm Mar 09 '21 at 20:48

0 Answers0