簡體   English   中英

線程模塊

[英]Threading module

有一個問題,我是線程方面的新手,我編寫了這段代碼....

import threading
from colorama import *
import random
import os

listax = [Fore.GREEN,Fore.YELLOW,Fore.RED]
print(random.choice(listax))

def hola():
    import requests
    a = requests.get('https://google.com')
    print(a.status_code)

if __name__ == "__main__":
    t1 = threading.Thread(target=hola)
    t2 = threading.Thread(target=hola)
    t3 = threading.Thread(target=hola)

    t1.start()
    t2.start()
    t3.start()

    t1.join()
    t2.join()
    t3.join()

如果我執行 3 次代碼,output 會顯示 3 次,但我的問題是,例如,如果我有大代碼並且全部開始於:

def main():
    code...

如何添加多線程以實現快速工作,我看到我可以添加 1 個線程,如果我添加 3 個線程,output 顯示 3 次,但是我可以如何做到這一點,例如在沒有 output 重復 10 的情況下將 10 個線程添加到同一任務使用系統資源盡可能快地執行此操作的時間?

您可以簡單地使用 for 循環。

number_of_threads 是您要運行的線程數

for _ in range(number_of_threads):

    t = threading.Thread(target=hola)
    t.join()
    t.start()

我試圖使用你給我的代碼循環

# Python program to illustrate the concept
# of threading
# importing the threading module
import threading
from colorama import *
import random
import os

listax = [Fore.GREEN,Fore.YELLOW,Fore.RED]
print(random.choice(listax))

"""
def print_cube(num):
    function to print cube of given num
    print("Cube: {}".format(num * num * num))
"""  
def print_square():
    num = 2
    """
    function to print square of given num
    """
    print("Square: {}".format(num * num))
def hola():
    import requests
    a = requests.get('https://google.com')
    print(a.status_code)
  
if __name__ == "__main__":
    for j in range(10):
        t1 = threading.Thread(target=hola)
        t1.start()
        t1.join()

但是當我運行代碼時,代碼每次運行 1 次打印,在我的情況下,給我 200 1 秒后再次 200 和 200 (x 10 次,因為我添加了 10 個線程)

但我想知道如何在不向我展示 10 output 的情況下盡可能快地執行此操作,只是我希望代碼執行 1 次打印,但例如使用 10 個線程盡可能快

多線程不會神奇地加速你的代碼。 您可以將代碼分成可以同時運行的塊。 當您創建 3 個運行hola的線程時,您不是“使用 3 個線程運行hola一次”,而是“運行hola三次,每次都在不同的線程中。

盡管多線程用於並行執行計算,但最常見的 python 解釋器 (CPython) 是使用鎖 (GIL) 實現的,該鎖一次只允許一個線程運行。 有些庫會在執行 CPU 密集型工作之前釋放 GIL,因此 python中的線程對於執行 CPU 密集型工作很有用。 此外,I/O 操作釋放 gil,因此 python 中的多線程非常適合 I/O 工作。

例如,假設您需要訪問三個不同的站點。 您可以依次訪問它們,一個接一個:

import requests

sites = ['https://google.com', 'https://yahoo.com', 'https://rae.es']

def hola(site):
    a = requests.get(site)
    print(site, " answered ", a.status_code)

for s in sites:
    hola(s)

或同時(同時)使用線程:

import requests
import threading

sites = ['https://google.com', 'https://yahoo.com', 'https://rae.es']

def hola(site):
    a = requests.get(site)
    print(site, " answered ", a.status_code)

th = [threading.Thread(target=hola, args=(s, )) for s in sites]
for t in th:
    t.start()
for t in th:
    t.join()

請注意,這是一個簡單的示例:output 可能會被打亂,您無法訪問返回值等。對於此類任務,我將使用線程池。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM