Simple implementation code of process pool in python

不言
Release: 2018-10-08 16:22:42
forward
2731 people have browsed it

The content of this article is about the simple implementation code of process pool in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Go back to python and use the python process pool.

I remember during the previous interview, the interviewer asked: Do you know the default parameters of the process pool? I didn't answer, but later I found out that there are default parameters. Let’s take a look at its default parameters

1. Without parameters

from multiprocessing.pool import Pool
from time import sleep
def fun(a):
    sleep(5)
    print(a)

if __name__ == '__main__':
    p = Pool()      # 这里不加参数,但是进程池的默认大小,等于电脑CPU的核数
                    # 也是创建子进程的个数,也是每次打印的数字的个数
    for i in range(10):
        p.apply_async(fun, args= (i, ))
    p.close()
    p.join()        # 等待所有子进程结束,再往后执行
    print("end")
Copy after login

2. With parameters5

from multiprocessing.pool import Pool
from time import sleep
def fun(a):
    sleep(5)
    print(a)
if __name__ == '__main__':
    p = Pool(5)     # 最多执行5个进程,打印5个数
    for i in range(10):
        p.apply_async(fun, args= (i, ))
    p.close()
    p.join()        # 等待所有子进程结束,再往后执行
    print("end")
Copy after login

The above is the detailed content of Simple implementation code of process pool in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!