python多进程———9、multiprocessing多进程编程

python多进程的multiprocessing的用法跟多线程threading的用法基本差不多,直接上代码吧

import multiprocessing
import os
import  time
#fork()只能在linux中使用
# pid = os.fork()
# if pid == 0:
#     print("子进程{},父进程是{}".format(os.getpid(),os.getppid()))
# else:
#     print("我是父进程:{}".format(pid))
# time.sleep(2)

def get_html(n):
    time.sleep(n)
    print("sub_processing success!")
    return n

if __name__ == "__main__":
    # progress = multiprocessing.Process(target=get_html,args=(2,))
    # print(progress.pid)
    # progress.start()
    # progress.join()
    # print("mian progress end")

    #如何使用multiprocessing中进程池
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    # result = pool.apply_async(get_html,args=(3,))
    # pool.close()
    # pool.join()
    # print(result.get())

    #imap and imap_unordered
    for result in pool.imap_unordered(get_html,[1,3,2,4]):
        print("{} sleep success!".format(result))

猜你喜欢

转载自blog.csdn.net/sinat_34461756/article/details/83897340