线程模块



有个问题,我是线程方面的新手,我做了这个代码。。。。

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次代码,输出显示3次,但我的问题是,例如,如果我有大代码,并且所有代码都以开头

def main():
code...

我如何添加多个线程来快速工作,我看到我可以添加1个线程,如果我添加3个线程,输出显示3次,但我如何做到这一点,例如,在同一任务中添加10个线程,而输出不重复10次,以便使用系统资源尽可能快地执行?

多线程并不能神奇地加速代码。这取决于您将代码分成可以并发运行的块。当您创建3个运行hola的线程时;使用3个线程运行CCD_ 2一次";,但你是";运行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()

请注意,这是一个简单的例子:输出可能会被打乱,你不能访问返回值,等等。对于这类任务,我会使用线程池。

我试图使用你给我的代码的循环

# 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次打印,在我的情况下,请给我2001秒后再次200和200再次(x 10次,因为我添加了10个线程(

但我想知道我如何在不显示10输出的情况下尽可能快地执行,我只想让代码打印1次,但用10线程尽可能快,例如

您可以简单地使用for循环。

number_of_threads是要运行的线程数

for _ in range(number_of_threads):
t = threading.Thread(target=hola)
t.start()
t.join()

最新更新