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()

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

不会

相关推荐
程序员三藏30 分钟前
使用Docker和Selenium构建自动化测试环境
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
CaracalTiger38 分钟前
本地部署 Stable Diffusion3.5!cpolar让远程访问很简单!
java·linux·运维·开发语言·python·微信·stable diffusion
api_180079054601 小时前
【技术教程】Python/Node.js 调用拼多多商品详情 API 示例详解
大数据·开发语言·python·数据挖掘·node.js
0小豆02 小时前
智能字幕校准系统实战(二):6级匹配算法从精确到模糊的全链路解析
python·nlp·算法设计·spacy·ai算法·时间序列对齐
jerryinwuhan2 小时前
Python数据挖掘之回归
python·数据挖掘·回归
ColderYY2 小时前
python和mongodb交互
python·mongodb
c++服务器开发2 小时前
掌握RAG系统的七个优秀GitHub存储库
人工智能·python·github·rag
AI的费曼精神2 小时前
Python装饰器入门:让你的代码更优雅
python
熬夜敲代码的小N3 小时前
仓颉ArrayList动态数组源码分析:从底层实现到性能优化
数据结构·python·算法·ai·性能优化
yumgpkpm3 小时前
Hadoop大数据平台在中国AI时代的后续发展趋势研究CMP(类Cloudera CDP 7.3 404版华为鲲鹏Kunpeng)
大数据·hive·hadoop·python·zookeeper·oracle·cloudera