0
from time import perf_counter, sleep
import threading


def foo(bar):
    some_func(bar) # takes longer with higher values of bar


if __name__ == "__main__":
    threads = []
    for i in range(15):
        threads.append(threading.Thread(target=func, args=(i,)))
    for i in range(15):
        threads[i].start()
    for i in range(15):
        threads[i].join()
        if sum_condition: # condition is from user input, so no way of knowing when it'll be true
            # kill all threads/join all threads
            pass

I don't know how to join all the threads when the condition is met, and the function some_func is from a library, so I cannot exit out of it. Is there any way to join all these threads/stop the function so the threads can return?

BanjoMan
  • 93
  • 5
  • Is your question: how do I make all the threads exit when sum_condition is met? Stopping threads versus joining on a thread are very different things (or is it that you want to do both?) so I do not really understand the question. – JRose Aug 10 '22 at 06:03
  • 3
    Running threads that may have to be "killed" is rarely a good idea. See: https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread – DarkKnight Aug 10 '22 at 06:27

1 Answers1

0
from time import perf_counter, sleep
import threading


# change/add code here
def foo(bar, running):
    while running.is_set():
# change/add code here
        some_func(bar) # takes longer with higher values of bar


if __name__ == "__main__":
    threads = []
    # change/add code here
    running = threading.Event()
    running.set()
    # change/add code here
    for i in range(15):
        threads.append(threading.Thread(target=func, args=(i,)))
    for i in range(15):
        threads[i].start()
    for i in range(15):
    # change/add code here
        if sum_condition: # condition is from user input, so no way of knowing when it'll be true
            # kill all threads/join all threads
            running.clear()
        threads[i].join()
    # change/add code here

How to close a thread when multithreading?

lam vu Nguyen
  • 433
  • 4
  • 9