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()?

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 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. – tdelaney Apr 26 '18 at 01:03
  • But you can `threading.enumerate()` and then decide if you can do [something like this](https://stackoverflow.com/a/325528/3424892). – lalengua Apr 26 '18 at 01:08

1 Answers1

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()
tdelaney
  • 73,364
  • 6
  • 83
  • 116