python中线程/线程池,进程/进程池的创建

创建子线程

python 复制代码
    # 创建子线程
    t1 = threading.Thread(target=job,args=(1,))
    # 执行子线程
    t1.start()
    # 等待子线程执行
    print("waiting threading")
    t1.join()
    print("threading done")

创建子进程

python 复制代码
    # 创建子进程
    p1 = multiprocessing.Process(target=job,args=(1,),name="processing-1")
    # 执行子进程
    p1.start()
    # 等待子进程执行
    p1.join()

创建线程池

python 复制代码
    # 创建线程池
    threadPool = ThreadPool(2)
    start = time.time()
    threadPool.map_async(func=job,iterable=(5,5,5,5))
    threadPool.close()
    threadPool.join()
    end = time.time()
    print(end-start)

创建进程池

python 复制代码
    # 创建进程池
    threadPool = Pool(2)
    start = time.time()
    threadPool.map_async(func=job, iterable=(5, 5, 5, 5))
    threadPool.close()
    threadPool.join()
    end = time.time()
    print(end - start)

完整代码

python 复制代码
import threading
import multiprocessing
import time
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool
import os
def job(a):
    time.sleep(a)
    print(f"sleep: {a}")
    print(f"process id is :{os.getpid()}")
def test():
    # 创建子线程
    t1 = threading.Thread(target=job,args=(1,))
    # 执行子线程
    t1.start()
    print(t1.ident)
    # 等待子线程执行
    t1.join()
    # 创建子进程
    p1 = multiprocessing.Process(target=job,args=(1,),name="processing-1")
    # 执行子进程
    p1.start()
    # 等待子进程执行
    p1.join()

    # 创建线程池
    threadPool = ThreadPool(2)
    start = time.time()
    threadPool.map_async(func=job,iterable=(5,5,5,5))
    threadPool.close()
    threadPool.join()
    end = time.time()
    print(end-start)

    # 创建进程池
    threadPool = Pool(2)
    start = time.time()
    threadPool.map_async(func=job, iterable=(5, 5, 5, 5))
    threadPool.close()
    threadPool.join()
    end = time.time()
    print(end - start)

if __name__ == '__main__':
    print(f"main processid {os.getpid()}")
    test()

线程/进程睡眠情况下,进程池会不会新创建线程?

不会

相关推荐
码界奇点2 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
Laravel技术社区3 小时前
pytesseract 中英文 识别图片文字
python
生骨大头菜4 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务
绝不收费—免费看不了了联系我4 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
xqqxqxxq5 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python
最晚的py5 小时前
Python抓取ZLibrary元数据
爬虫·python
咖啡续命又一天5 小时前
Trae CN IDE 中 Python 开发的具体流程和配置总结
开发语言·ide·python·ai编程
IT·小灰灰6 小时前
告别“翻墙“烦恼:DMXAPI让Gemini-3-pro-thinking调用快如闪电
网络·人工智能·python·深度学习·云计算
山海青风7 小时前
语音合成 - 用 Python 合成藏语三大方言语音
开发语言·python·音视频
mikejahn7 小时前
爬取CECS网站征求意见栏目的最新信息
python