python 多线程和多进程的程序实现

本文深入探讨Python中的多线程和多进程编程,通过实例演示如何使用multiprocessing模块进行多进程处理,包括进程池和进程间通信的Queue应用,以及与多线程的对比测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 摘要:熟悉python中关于多线程和多进程的程序实现。


from multiprocessing import Process
from multiprocessing import Pool
from multiprocessing import Queue
import time
import threading


########################多进程设计##########################################
def f(n):
    time.sleep(1)
    print('{0}*{0}={1}'.format(n,n*n))


def count_test():
    S=time.time()
    for i in range(10): # 相对于开辟了10个进程
        p=Process(target=f,args=(i,)) # 一个process代表一个进程对象
        p.start()
    p.join()
    E=time.time()
    print("time total :",E-S)

########################进程池设计##########################################
def ff(x):
    print("{0}*{0}={1}".format(x,x*x))
    time.sleep(1)
    return x*x

# 进程池Pool,用于批量创建子进程,可以灵活控制子进程的数量
def get_Pool():
    pool=Pool(processes=5) # 定义启动的进程数量
    res_list=[]
    for i in range(20):
        res=pool.apply_async(ff,args=(i,))
        print('----',i)
        res_list.append(res)
    pool.close() # 关闭进程池,不再接受进的进程请求,但已经接受的进程还是会继续执行
    pool.join() # 主进程堵塞(就是不执行join下面的语句)
    for i in res_list:
        print('result:',i.get(timeout=2)) #没有设置timeout,将会一直等待结果,
#如果设置了timeout,超过timeout将引发multiprocessing.TimeoutError异常

# 多进程和多线程的测试对比
lock=threading.Lock()
def multiprocess_thread_test():
    info=[]
    print('----------Process-------------')
    for i in range(10):
        p=Process(target=runrun,args=(info,i))
        p.start()
    p.join()
    time.sleep(1)
    info=[]
    print("----------threading---------")
    for i in range(10):
        p=threading.Thread(target=runrun,args=(info,i))
        p.start()
    p.join()

# ----------Process-------------
# [0]
# [1]
# [2]
# [3]
# [4]
# [5]
# [6]
# [7]
# [8]
# [9]
# ----------threading---------
# [0]
# [0, 1]
# [0, 1, 2]
# [0, 1, 2, 3]
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3, 4, 5]
# [0, 1, 2, 3, 4, 5, 6]
# [0, 1, 2, 3, 4, 5, 6, 7]
# [0, 1, 2, 3, 4, 5, 6, 7, 8]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

def runrun(info_list,n):
    lock.acquire()
    info_list.append(n)
    lock.release()
    print('%s' %info_list)


## 进程间通信 Queue
def writeQ(q):
    for i in ['a','b','c','d','e','f','g']:
        print('put %s to queue' %i)
        q.put(i)
        time.sleep(1)

def readQ(q):
    while True:
        v=q.get(True)
        print('get %s from queue' %v)


def queue_test():
    q=Queue()
    pw=Process(target=writeQ,args=(q,))
    pr=Process(target=readQ,args=(q,))
    pw.start()
    pr.start()
    pr.terminate()
    pr.join()
    print("finish !!!!")

if __name__ == '__main__':
    queue_test()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值