首页 > 解决方案 > 在完成循环之前执行 for 循环之后的代码

问题描述

我一直在搜索,但我找不到我的代码有什么问题。它是一个代理检查器,我用线程制作了一个 for 循环,并希望它在完成循环后打印“FINISHED”:

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

但它甚至在检查一半代理之前打印“完成”,我希望它在完成 for 循环后这样做。

感谢您的帮助:)

标签: pythonpython-3.xmultithreadingfor-looppython-requests

解决方案


在循环启动每个线程后,您需要加入每个线程以等待它完成。

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

推荐阅读