Como retornar valores de um thread

Resumo : neste tutorial, você aprenderá como retornar valores de um thread filho para o thread principal estendendo a threading.Threadclasse.

Quando um programa Python é iniciado, ele possui um único thread chamado thread principal . Às vezes, você deseja descarregar tarefas de E/S para novos threads e executá-las simultaneamente. Além disso, você também pode obter os valores de retorno desses threads no thread principal.

Para retornar um valor de um thread, você pode estender a classe Thread e armazenar esse valor na instância da classe.

O exemplo a seguir ilustra como verificar um URL especificado e retornar seu código de status HTTP em um thread separado:

from threading import Thread
import urllib.request


class HttpRequestThread(Thread):
    def __init__(self, url: str) -> None:
        super().__init__()
        self.url = url
        self.http_status_code = None
        self.reason = None

    def run(self) -> None:
        try:
            response = urllib.request.urlopen(self.url)
            self.http_status_code = response.code
        except urllib.error.HTTPError as e:
            self.http_status_code = e.code
        except urllib.error.URLError as e:
            self.reason = e.reason


def main() -> None:
    urls = [
        'https://httpstat.us/200',
        'https://httpstat.us/400'
    ]

    # create new threads
    threads = [HttpRequestThread(url) for url in urls]

    # start the threads
    [t.start() for t in threads]

    # wait for the threads to complete
    [t.join() for t in threads]

    # display the URLs with HTTP status codes
    [print(f'{t.url}: {t.http_status_code}') for t in threads]


if __name__ == '__main__':
    main()


def main() -> None:
    urls = [
        'https://httpstat.us/200',
        'https://httpstat.us/400'
    ]

    # create new threads
    threads = [HttpRequestThread(url) for url in urls]

    # start the threads
    [t.start() for t in threads]

    # wait for the threads to complete
    [t.join() for t in threads]

    # display the URLs with HTTP status codes
    [print(f'{t.url}: {t.http_status_code}') for t in threads]

Linguagem de código:  Python  ( python )

Saída:

ttps://httpstat.us/200: 200
https://httpstat.us/400: 400Linguagem de código:  Python  ( python )

Como funciona.

Primeiro, defina a HttpRequestThreadclasse que estende a Threadclasse:

class HttpRequestThread(Thread):
# ...Linguagem de código:  Python  ( python )

Segundo, defina o __init__()método que aceita uma URL. Dentro do __init__()método adiciona variáveis url​​, http_status_codee reasonde instância. O http_status_codeirá armazenar o código de status do urlno momento da verificação e reasonarmazenará a mensagem de erro caso ocorra um erro:

def __init__(self, url: str) -> None:
    super().__init__()
    self.url = url
    self.http_status_code = None
    self.reason = NoneLinguagem de código:  Python  ( python )

Terceiro, substitua o run()método que usa a urllibbiblioteca para obter o código de status HTTP do URL especificado e atribua-o ao http_status_codecampo. Se ocorrer um erro, atribui a mensagem de erro ao reasoncampo:

def run(self) -> None:
    try:
        response = urllib.request.urlopen(self.url)
        self.http_status_code = response.code
    except urllib.error.HTTPError as e:
        self.http_status_code = e.code
    except urllib.error.URLError as e:
        self.reason = e.reasonLinguagem de código:  Python  ( python )

Posteriormente, podemos acessar url, http_status_codee reasona partir da instância da HttpRequestThreadclasse.

Quarto, defina a main()função que cria instâncias da HttpRequestThreadclasse, inicia os threads, espera que eles sejam concluídos e obtém o resultado das instâncias:

def main() -> None:
    urls = [
        'https://httpstat.us/200',
        'https://httpstat.us/400'
    ]

    # create new threads
    threads = [HttpRequestThread(url) for url in urls]

    # start the threads
    [t.start() for t in threads]

    # wait for the threads to complete
    [t.join() for t in threads]

    # display the URLs with HTTP status codes
    [print(f'{t.url}: {t.http_status_code}') for t in threads]Linguagem de código:  Python  ( python )

Resumo

  • Estenda a Threadclasse e defina as variáveis ​​de instância dentro da subclasse para retornar os valores de um thread filho para o thread principal.

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *