python 多进程——使用进程池,多进程消费的数据)是一个队列的时候,他会自动去队列里依次取数据

我的mac 4核,因此每次执行的时候同时开启4个线程处理:

# coding: utf-8

import time
from multiprocessing import Pool


def long_time_task(name):
    print 'task %s starts running' % name
    time.sleep(3)
    print 'task %s ends running --3 seconds' % name


if __name__ == '__main__':
    start = time.time()
    p = Pool()
    for i in range(10):  # CPU有几核,每次就取出几个进程
        p.apply_async(func=long_time_task, args=(i,))
    p.close()  # 调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了
    p.join()  # 对Pool对象调用join()方法会等待所有子进程执行完毕
    end = time.time()
    print('多进程(非阻塞)执行共需时间为:%.2f' % (end - start))

运行效果:

task 0 starts running
task 1 starts running
task 2 starts running
task 3 starts running
task 0 ends running --3 seconds
task 1 ends running --3 seconds
task 3 ends running --3 seconds
task 2 ends running --3 seconds
task 4 starts running
task 5 starts running
task 6 starts running
task 7 starts running
task 5 ends running --3 seconds
task 4 ends running --3 seconds
task 7 ends running --3 seconds
task 6 ends running --3 seconds
task 8 starts running
task 9 starts running
task 8 ends running --3 seconds
task 9 ends running --3 seconds
多进程(非阻塞)执行共需时间为:9.13

解释:

CPU先取出0-3号进程,执行完毕后,4~8号进程才开始执行。0-3号进程花了3秒钟,4~8号 进程也花了3秒。最后两个进程9,10又花了三秒,一共9秒。

也就意味着,我的代码可以这样写,当history_ddos(多进程消费的数据)是一个队列的时候,他会自动去队列里依次取数据

    f = open("history_ddos.json", "r")
    history_ddos = json.load(f)
    f.close()

    # 10表示进程池中最多有10个进程一起执行
    p = Pool(10)
    for item in history_ddos:
        # find_ddos_botnet(item)
        p.apply_async(func=find_ddos_botnet(), args=(item,))
    p.close()
    p.join()

猜你喜欢

转载自www.cnblogs.com/bonelee/p/9645429.html