python的多进程/多线程及其返回值的获取,类比Java多线程

文章目录

  • 一、不考虑返回值时可直接使用threading/multiprocessing,类似的Java的Thread及Runable也无法获取返回值(Callable可以)
  • 二、使用ThreadPoolExecutor/ProcessPoolExecutor,同Java的ThreadPoolExecutor一样从Future获取子线程/进程的返回值会阻塞
  • 三、使用asyncio协程实现“多线程”返回值获取
  • 四、使用multiprocessing 的Pool可以通过callback回调函数来获取多进程的返回值,类似Java spring框架的ThreadPoolTaskExecutor#submitListenable(...)

python为解释性语言,解释器全局锁使同一时刻只能有一个线程执行,故python的多线程不是真正的多线程,在io密集型应用有更好的‘并行’效果,但python多进程能真正并很简单的实现并行。

一、不考虑返回值时可直接使用threading/multiprocessing,类似的Java的Thread及Runable也无法获取返回值(Callable可以)

import threading
import multiprocessing
import time
import psutil

def calc_square(sleep_second,n):
    time.sleep(sleep_second)
    print("输入:",n)
    return n**2

if __name__ == '__main__':
    #t1=threading.Thread(target=calc_square,args=(3,5))
    #t2=threading.Thread(target=calc_square,args=(3,6))
    t1=multiprocessing.Process(target=calc_square,args=(3,5))
    t2=multiprocessing.Process(target=calc_square,args=(3,6))

    t1.start()
    t2.start()
    t1.join()
    t2.join()

二、使用ThreadPoolExecutor/ProcessPoolExecutor,同Java的ThreadPoolExecutor一样从Future获取子线程/进程的返回值会阻塞

# -*- coding: utf-8 -*-
import time
import os
from concurrent.futures import ThreadPoolExecutor
#from concurrent.futures.process import ProcessPoolExecutor
#from concurrent.futures.thread import ThreadPoolExecutor


def calc_square(sleep_second, n):
    time.sleep(sleep_second)
    print(f"输入:{n},{os.getpid()}")
    return n ** 2


if __name__ == '__main__':
    pool = ThreadPoolExecutor(max_workers=4)
    #pool = ProcessPoolExecutor(max_workers=4)
    for i in (range(10)):
        future = pool.submit(calc_square, i, i)
        print(f"thread:{i}, {future.result()}")

三、使用asyncio协程实现“多线程”返回值获取

# -*- coding: utf-8 -*-
import asyncio
import os

# 类似JS async await
async def calc_square(sleep_second, n):
    print(f"输入:{n},进程ID:{os.getpid()}")
    # 执行到这里await挂起当前任务,其它协程可以获取CPU时间片
    await asyncio.sleep(sleep_second)
    return n ** 2


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    future = asyncio.gather(calc_square(1, 1), calc_square(2, 2), calc_square(5, 5))
    future.add_done_callback(lambda res: print(res.result()))
    # 此处才真正开始伪并行运行
    loop.run_until_complete(future)

四、使用multiprocessing 的Pool可以通过callback回调函数来获取多进程的返回值,类似Java spring框架的ThreadPoolTaskExecutor#submitListenable(…)

# -*- coding: utf-8 -*-
import time
import os
from multiprocessing import Pool


def calc_square(sleep_second, n):
    print(f"输入:{n},进程ID:{os.getpid()}")
    time.sleep(sleep_second)
    return n ** 2


if __name__ == '__main__':
    pool = Pool(processes=8)
    for i in (range(10)):
        pool.apply_async(calc_square, args=(i, i ** 2), callback=lambda res: print(res))
    pool.close()
    pool.join()

你可能感兴趣的:(python,java,开发语言)