A
A
Andrey Romanov2021-11-08 12:06:14
Python
Andrey Romanov, 2021-11-08 12:06:14

How to run a loop in 10 threads?

Good day. I have a for in loop, I need to run it on 10 threads at the same time. Can you please tell me how to do this in Python? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery Mamontov, 2021-11-18
@roni43

Good)
Look at this code, suddenly it will help you.

import threading
#pip install requests
import requests


def get_status(url, results):
    results[url] = requests.get(url).status_code


sites = ['https://www.google.com/', 'https://www.youtube.com/',
         'https://pastebin.com/', 'https://ru.wikipedia.org/',
         'https://yandex.ru/', 'https://www.pornhub.com/',
         'https://vk.com/', 'https://www.reddit.com/',
         'https://qna.habr.com/', 'https://stackoverflow.com/']*5


results = {}
workers = [threading.Thread(target=get_status(sites[f], results)) for f in range(10)]

for worker in workers:
    worker.start()

for worker in workers:
    worker.join()

for k, v in results.items():
    print(k, v)

D
Denis, 2021-11-18
@Sat0shi

Better look into ThreadPoolExecutor and ProcessPoolExecutor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question