欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python多进程使用及线程池的使用方法

程序员文章站 2022-04-15 11:06:38
多进程:主要运行multiprocessing模块 线程池:主要运用了未来模块!下面例子,第一个是正常,第二第线程池,第三个用运行了2个线程池,会排队 ......

多进程:主要运行multiprocessing模块

import os,time
import sys
from multiprocessing import process
 
class myprocess(process):
    """docstring for myprocess"""
    def __init__(self, arg, callback):
        super(myprocess, self).__init__()
        self.arg = arg
        self.callback = callback

    def run(self):
        self.callback(self.arg)
        

def test(arg):
    print("子进程{}开始>>> pid={}".format(arg,os.getpid()))
    for i in range(1,5):
        sys.stdout.write("子进程{}运行中{}\r".format(arg,i))
        sys.stdout.flush()
        time.sleep(1)
def main():
    print("主进程开始>>> pid={}".format(os.getpid()))
    myp=myprocess(1,test)
    myp.start()
    myp2=myprocess(2,test)
    myp2.start()
    myp.join()
    myp2.join()
    print("主进程终止")
 
if __name__ == '__main__':
    main()

线程池:主要运用了未来模块!下面例子,第一个是正常,第二第线程池,第三个用运行了2个线程池,会排队

from concurrent.futures import threadpoolexecutor
import time

def sayhello(a):
    print("hello: "+a)
    time.sleep(2)

def main():
    seed=["a","b","c"]
    start1=time.time()
    for each in seed:
        sayhello(each)
    end1=time.time()
    print("time1: "+str(end1-start1))
    start2=time.time()
    with threadpoolexecutor(3) as executor:
        for each in seed:
            executor.submit(sayhello,each)
    end2=time.time()
    print("time2: "+str(end2-start2))
    start3=time.time()
    with threadpoolexecutor(2) as executor1:
        executor1.map(sayhello,seed)
    end3=time.time()
    print("time3: "+str(end3-start3))

if __name__ == '__main__':
    main()