Step1、线程的概念: 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。
Step2、本文是想通过多线程这个技术点来讲解并发操作是否可以提高效率
具体代码示例如下截图所示:
# coding:gbk import time,threading,requests #配置:模拟压力运行状态 Thread_Number =100 #并发线程总数 #失败次数 global Error_number Error_number = 0 #请求地址 Base_url = "http://dict.baidu.com" #具体的http请求处理函数,负责处理单个任务 def http_request(threadname): response=requests.get(url=Base_url,params={'wd':'python'}) print(response.url,response.status_code,response.reason) print("["+str(threadname)+"]",response.status_code) if int(response.status_code) != 200: Error_number += 1 def main(): start_time =time.time() #开始时间 Threads = [] for i in range(Thread_Number): ''' target: 指定这个线程去哪个函数里面去执行代码 args: 指定将来调用 函数的时候传递什么数据过去 args参数指定的一定是一个元组类型 ''' t = threading.Thread(target=http_request,args=("threading-"+str(i),)) #创建线程 t.setDaemon(True)#daemon 属性默认是False,这使得MainThread需要等待他的结束,自身才结束。 Threads.append(t) #讲线程存放到list中 for t in Threads: t.start() #开始执行该线程 for t in Threads: t.join() #可以让主线程等待所有的线程都执行完毕 end_time =time.time() print("=========================================") print("URL:", Base_url) print("任务总数量:",Thread_Number) print("总耗时(秒):",end_time-start_time) print("每次请求耗时(秒):", (end_time-start_time) / Thread_Number) print("错误数量:", Error_number) if __name__ == '__main__': main()Step3、执行结果:
[threading-89] 200 https://dict.baidu.com/?wd=python 200 OK [threading-93] 200 https://dict.baidu.com/?wd=python 200 OK [threading-95] 200 https://dict.baidu.com/?wd=python 200 OK [threading-87] 200 ========================================= URL: http://dict.baidu.com 任务总数量: 100 总耗时(秒): 1.5593395233154297 每次请求耗时(秒): 0.015593395233154297 错误数量: 0**Step4、普通的循环调用100次请求与最终结果,代码如下: **
def normal_run(): start_time =time.time() #开始时间 for i in range(100): http_request("threading-"+str(i)) end_time = time.time() print("总耗时(秒)" ,end_time - start_time) if __name__ == '__main__': normal_run() [threading-95] 200 https://dict.baidu.com/?wd=python 200 OK [threading-96] 200 https://dict.baidu.com/?wd=python 200 OK [threading-97] 200 https://dict.baidu.com/?wd=python 200 OK [threading-98] 200 https://dict.baidu.com/?wd=python 200 OK [threading-99] 200 总耗时(秒) 39.05704641342163