Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wait for one threading to finish then run another threading

I need to open multiple chrome drivers with selenium, then execute my script by threading in them.
How to make it wait until first threading is finished and then start second threading.
time.sleep(x) wont work for me, as I do not know how much time would first threading take and I need second threading to start as soon as first one is finished.

import time
import threading
from selenium import webdriver


mydrivers=[]
tabs = []
class ActivePool(object):
    def __init__(self):
        super(ActivePool, self).__init__()
        self.active = []
        self.lock = threading.Lock()
    def makeActive(self, name):
        with self.lock:
            self.active.append(name)
    def makeInactive(self, name):
        with self.lock:
            self.active.remove(name)
                    
def main_worker(s):
    #Driver State
    global tabs
    global mydrivers
    mydrivers.append(webdriver.Chrome())
    tabs.append(False)

def worker(s, pool):
        with s:
            global tabs
            global mydrivers
            name = threading.currentThread().getName()
            pool.makeActive(name)
            x = tabs.index(False)
            tabs[x] = True
            mydrivers[x].get("https://stackoverflow.com")
            time.sleep(15)
            pool.makeInactive(name)
            tabs[x]= False   



for k in range(5):
    t = threading.Thread(target=main_worker, args=(k,))
    t.start()

# How to make it wait until above threading is finished and then start below threading

pool = ActivePool()
s = threading.Semaphore(5)
for j in range(100):
    t = threading.Thread(target=worker, name=j, args=(s, pool))
    t.start()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thds = []
for k in range(5):
    thds.append( threading.Thread(target=main_worker, args=(k,)))
for t in thds:
    t.start()
for t in thds:
    t.join()

Or, even:

thds = [threading.Thread(target=main_worker, args=(k,)) for k in range(5)]
for t in thds:
    t.start()
for t in thds:
    t.join()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading