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

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

不会

相关推荐
Hgfdsaqwr4 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
开发者小天4 小时前
python中For Loop的用法
java·服务器·python
老百姓懂点AI5 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
喵手7 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列
Suchadar7 小时前
if判断语句——Python
开发语言·python
ʚB҉L҉A҉C҉K҉.҉基҉德҉^҉大7 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
喵手7 小时前
Python爬虫零基础入门【第九章:实战项目教学·第14节】表格型页面采集:多列、多行、跨页(通用表格解析)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·表格型页面采集·通用表格解析
0思必得08 小时前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化
莫问前路漫漫8 小时前
WinMerge v2.16.41 中文绿色版深度解析:文件对比与合并的全能工具
java·开发语言·python·jdk·ai编程
木头左8 小时前
Backtrader框架下的指数期权备兑策略资金管理实现与风险控制
python