python之进程,线程,协程
进程+线程
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: yunhgu
@time: 2021/5/21 14:55
@file: Process_async.py
@description:
"""
import time
import asyncio
import os
import psutil
import threading
from concurrent.futures import ProcessPoolExecutor
async def a():
pid = os.getpid()
ps = psutil.Process(pid)
print(f"进程id:{pid} 线程数:{ps.num_threads()} 线程id:{threading.current_thread().ident}")
await asyncio.sleep(1)
async def b():
await a()
def run():
loop = asyncio.get_event_loop()
task = [b() for j in range(2)]
loop.run_until_complete(asyncio.wait(task))
loop.close()
if __name__ == '__main__':
start_time = time.time()
p = ProcessPoolExecutor(4)
for i in range(2):
p.submit(run)
p.shutdown(wait=True)
print(f"耗费时间:{time.time() - start_time}")
进程id:39100 线程数:5 线程id:39924
进程id:39100 线程数:5 线程id:39924
进程id:39216 线程数:5 线程id:31592
进程id:39216 线程数:5 线程id:31592
耗费时间:2.4648985862731934
进程+线程
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: yunhgu
@time: 2021/5/21 15:23
@file: Process_thread.py
@description:
"""
import time
import os
import psutil
import threading
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def a():
pid = os.getpid()
ps = psutil.Process(pid)
print(f"进程id:{pid} 线程数:{ps.num_threads()} 线程id:{threading.current_thread().ident}")
time.sleep(1)
def run():
t = ThreadPoolExecutor()
for j in range(2):
t.submit(a)
t.shutdown(wait=True)
if __name__ == '__main__':
start_time = time.time()
p = ProcessPoolExecutor(4)
for i in range(2):
p.submit(run)
p.shutdown(wait=True)
print(f"耗费时间:{time.time() - start_time}")
进程id:35440 线程数:5 线程id:38792
进程id:35440 线程数:6 线程id:31916
进程id:34316 线程数:5 线程id:37796
进程id:34316 线程数:6 线程id:38384
耗费时间:2.2368392944335938
不论你在什么时候开始,重要的是开始之后就不要停止。
不论你在什么时候结束,重要的是结束之后就不要悔恨。