1. 程式人生 > >多進程模塊:multiprocessing

多進程模塊:multiprocessing

import target pre oot 會同 即使 world tar RoCE

多進程:

(1) 前面我們學習的多線程,其實算不上真正的多線程,即使你開了很多個線程,在同一時間內只能有一個CPU核數來處理一個線程
(2) 在 python 中,多進程算得上是真正的多線程,假設你的CPU有四核,如果開四個子進程,四個CPU核數會同時處理這四個子進程
(3) 在 threading 中,我們是通過 threading.Thread(target=function, args=(....)) 來創建一個對象,然後再通過對象的 start() 方法來運行一個子線程,多個子線程可以並發執行
(4) 在 multiprocessing 中,我們是通過 multiprocessing.Process(target=function, args=(....)) 來創建一個對象,然後再通過對象的 start() 方法來運行一個子進程,多個子進程可以並發執行

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import time
import multiprocessing

def fun():
    print hello world, os.getpid(), os.getppid()
    time.sleep(1)

for i in range(10):
    p = multiprocessing.Process(target=fun, args=())
    p.start()
[root@localhost ~]$ python 1.py 
hello world 
4056 4055 hello world 4057 4055 hello world 4058 4055 hello world 4059 4055 hello world 4060 4055 hello world 4061 4055 hello world 4062 4055 hello world 4063 4055 hello world 4064 4055 hello world 4065 4055

多進程模塊:multiprocessing