anhhpvnu
anhhpvnu

Reputation: 27

How to run multiple Thread in Python

I have all 50 chrome must run. I want to always run 5 chrome at the same time. If 1 in 5 chrome closes first, it will run 1 chrome new. Until 50 chrome finished.

Example: 5 chrome are running. If chrome 3 closes first, chrome 6 will run. So it always run 5 chrome at the same time.

How can I do it?

run_chrome = 50
thread = 5
def run_thread(thread_amount):
    my_thread = []
    for i in range(thread_amount):
        my_thread.append(threading.Thread(target=run_chrome_browser, args=[]))
    for t in my_thread:
        t.start()
    for t in my_thread:
        t.join()
while thread < run_chrome:
    run_thread(thread)
    run_chrome = run_chrome - thread
run_thread(run_chrome)

Upvotes: 1

Views: 417

Answers (1)

HALF9000
HALF9000

Reputation: 628

Thread-pool is one of solutions.

import time

from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(max_workers=5)

def chrome_app_func(i):
    print(f"Fake chrome app: {i}")
    time.sleep(10)
    print(f"Fake chrome app: {i} -- finished")


for i in range(50):
    pool.submit(chrome_app_func, i)

Upvotes: 2

Related Questions