user8876840
user8876840

Reputation:

Kill all threads python

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

Upvotes: 1

Views: 301

Answers (1)

tdelaney
tdelaney

Reputation: 77407

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

Upvotes: 1

Related Questions