1

Starting my script off with:

for i in range(threads): t = Thread(target=getSizes, args=(i,)) t.start() 

Then when one of the threads is able to get the variables needed for the other functions it does:

for i in range(threads): t = Thread(target=cart, args=(i, sizes, prod_name, product_id)) t.start() 

Is there any way to till all threads started on getSizes() and then start new threads on cart()?

2
  • You can't kill threads. You can write code in the thread to return (which kills the thread) when it detects a termination condition. If getSizes has a loop, it could check a semphore on each iteration. When one sets it, the others exit. Commented Apr 26, 2018 at 1:03
  • But you can threading.enumerate() and then decide if you can do something like this. Commented Apr 26, 2018 at 1:08

1 Answer 1

1

If your worker function does work in a loop, it can use a common resource like an Event to signal when work is complete and it should return. Here is an example

import threading import time import random def getSizes(done_event): while not done_event.is_set(): print("get size") if random.randint(0, 20) == 10: print("got size") done_event.set() do_cart() else: time.sleep(random.random()) print("sizes done") def do_getSizes(): event = threading.Event() threads = [] for i in range(5): t = threading.Thread(target=getSizes, args=(event,)) t.start() threads.append(t) for t in threads: t.join() def cart(): print("I haz the cartz") def do_cart(): time.sleep(1) threads = [] for i in range(5): t = threading.Thread(target=cart) t.start() threads.append(t) for t in threads: t.join() do_getSizes() 
Sign up to request clarification or add additional context in comments.

Comments