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

创建子线程

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

创建子进程

    # 创建子进程
    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)

完整代码

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

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

不会

相关推荐

  1. python中线/线进程/进程创建

    2024-02-18 06:48:02       51 阅读
  2. 进程线

    2024-02-18 06:48:02       25 阅读
  3. 线创建方式

    2024-02-18 06:48:02       39 阅读
  4. 一个线进入线工作流程

    2024-02-18 06:48:02       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-18 06:48:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-18 06:48:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-18 06:48:02       82 阅读
  4. Python语言-面向对象

    2024-02-18 06:48:02       91 阅读

热门阅读

  1. 学习Android的第十四天

    2024-02-18 06:48:02       51 阅读
  2. 【无标题】

    2024-02-18 06:48:02       51 阅读
  3. ABC341A-D题解

    2024-02-18 06:48:02       51 阅读
  4. 寿司转盘,用 C 编码

    2024-02-18 06:48:02       57 阅读
  5. Pytorch的安装教程,解决jupyter不能使用pytorch的问题

    2024-02-18 06:48:02       59 阅读
  6. 每日OJ题_算法_递归⑤力扣50. Pow(x, n)

    2024-02-18 06:48:02       62 阅读
  7. JVM的类的生命周期

    2024-02-18 06:48:02       48 阅读
  8. 2024年五大科技与创业趋势:从AI退热到IPO挑战

    2024-02-18 06:48:02       53 阅读
  9. MySQL定时备份及清理脚本

    2024-02-18 06:48:02       56 阅读