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

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

不会

相关推荐
Onebound_Ed8 分钟前
Python爬虫进阶:面向对象设计构建高可维护的1688商品数据采集系统
开发语言·爬虫·python
阿蔹32 分钟前
JavaWeb-Selenium 配置以及Selenim classnotfound问题解决
java·软件测试·python·selenium·测试工具·自动化
万粉变现经纪人1 小时前
如何解决 pip install 代理报错 407 Proxy Authentication Required 问题
windows·python·pycharm·beautifulsoup·bug·pandas·pip
李剑一1 小时前
Python学习笔记3
python
luod1 小时前
Python包
python
Mr Lee_2 小时前
Smali 文件生成dex装箱算法整合
开发语言·python·算法
电饭叔2 小时前
《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之一(Luhn算法解释)
android·java·python
小女孩真可爱2 小时前
大模型学习记录(八)---------RAG评估
linux·人工智能·python
刘晓倩2 小时前
Python3的Sequence
开发语言·python
ZhengEnCi2 小时前
一次多线程同步问题的排查:从 thread_count 到 thread.join() 的踩坑之旅
python·网络协议·tcp/ip