大家好,我是Afan
不理解单线程 与 多线程?敲几遍就好了
一、单线程 与 多线程 比较
from threading import Thread
import threading
import requests
import time
#请求任务
def request_task(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
requests.get(url,headers=headers)
time.sleep(0.5)
#获取线程名
thread_name = threading.current_thread().name
print(thread_name,'get',url)
#单线程
def singal_thread():
# 时间戳,距离1970年多少秒
start = time.time()
url = 'https://www.baidu.com/s?wd={}'
# 发送10个请求
for i in range(10):
request_task(url=url.format(i)) #调用
print('单线程耗时',time.time() - start)
#多线程
def multi_thread():
# 加入时间戳
start = time.time()
url = 'https://www.baidu.com/s?wd={}'
#线程池
thread_pool = []
for i in range(10):
t = Thread(target=request_task,args=(url.format(i),))
thread_pool.append(t)
# 开启线程任务
for i in thread_pool:
i.start()
#阻塞线程(等待线程执行完毕才执行打印语句)
for i in thread_pool:
i.join()
print('多线程耗时', time.time() - start)
if __name__ == '__main__':
# 测试单线程与多线程的速度
# singal_thread()
multi_thread()
二、多进程
from multiprocessing import Process
import os
def process_task(name):
#进程id
#获取进程号
pid = os.getpid()
#主进程
ppid = os.getppid()
print("start",name,'当前进程id',pid,'主进程id',ppid)
if __name__ == '__main__':
# 创建子进程,args参数传递列表为元组
# 注意:当元组中只有一个数据时,需要加逗号,否则为其他数据类型
p1 = Process(target=process_task,args=('afan',))
# 开始进程
p1.start()
p2 = Process(target=process_task,args=('afan2',))
p2.start()
三、进程池
import os
from multiprocessing import Pool
def fun(n):
print(os.getpid())
return n*n
if __name__ == '__main__':
#使用pool创建10个进程,过多的进程会导致系统崩溃
pool = Pool(processes=10)
list = [1,2,3,4,5,6,7,8,9,10]
#系统提供执行进程池的方式
pool.map(fun,list)
总结:一般我们使用多线程较多,速度快,多进程的使用了解下就好。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。