ApolloGod
ApolloGod

Reputation: 13

Code after a for loop being executed before finishing loop

I have been searching a lot, and I cannot find whats wrong with my code. Its a proxy checker, and I have made a for loop with threading, and want it to print "FINISHED" after finishing the loop:

def cthread():
    while len(proxies) > 0:
        proxy = proxies.pop(0)
        try:
            requests.get(url, proxies={'https':proxytype+"://"+proxy}, timeout=timeout)
            print(proxy, '< GOOD PROXY')
            with open('working.txt', 'a') as proxywork:
                proxywork.write(proxy + '\n')
                proxywork.flush()
        except:
            try:
                print(proxy, ' > BAD')
            except:
                print("ERROR")
for i in range(tc):
    threading.Thread(target=cthread).start()
configuration.close()
print("FINISHED")
time.sleep(900.0 - ((time.time() - starttime) % 900.0))

but it prints "FINISHED" before even checking a half of the proxies, and I want it to do so after finishing the for loop.

Thanks for helping :)

Upvotes: 1

Views: 65

Answers (1)

chepner
chepner

Reputation: 532208

You need to join each thread to wait for it to complete after the loop starts each thread.

threads = [threading.Thread(target=cthread) for _ in range(tc)]
for t in threads:
    t.start()

# Do stuff here while threads are running

# Now wait for all threads to complete
for t in threads:
    t.join()

configuration.close()
print("FINISHED")
time.sleep(900.0 - ((time.time() - starttime) % 900.0))

Upvotes: 2

Related Questions