1. python 怎麼運行一個新的進程
importmultiprocessing
#xxx是你的函數名,記住不要加括弧
#args是參數,是一個元組,如果只有一個參數則是args=(x,)
p=multiprocessing.Process(target=xxx,args=(x,y))
p.start()
2. python 多進程
os.fork()指令會創建另外一個進程,他的輸出源也是你的python command line或者其他IDE。所以你會看見2個提示符。另外,IDE要處理那麼多輸出源,當然會很卡。還有,你連打下3次這個命令,相當於對三個進程都進行了下達指令,所以這時候你的進程數目為8(看不懂的建議看小學數學)。你的各個進程的輸出會類似於打架,所以窗口會變得很慢。
建議:用pid來區分各個進程(os.fork()在父進程會返回pid,子進程會返回0),例如:
import os
import time
pid=os.fork()
if pid==0:
time.sleep(0.1);
print "Child."
else:
print "The child's pid is:"+str(pid)
//end
以上代碼中子進程我給他暫停0.1秒來防止與父進程的輸出「打架」,當然有更好的解決方法,由於字數限制不打出來了,具體就是鎖住輸出源,通過之後再解鎖,可以網路。
點贊、採納、轉發,素質三連,友誼你我他!
3. python 多進程問題
兩個進程如果要同時運行,star函數挨著一起寫
4. python可以多進程嗎
想要充分利用多核CPU資源,Python中大部分情況下都需要使用多進程,Python中提供了multiprocessing這個包實現多進程。multiprocessing支持子進程、進程間的同步與通信,提供了Process、Queue、Pipe、Lock等組件。
開辟子進程
multiprocessing中提供了Process類來生成進程實例
Process([group [, target [, name [, args [, kwargs]]]]])
group分組,實際上不使用
target表示調用對象,你可以傳入方法的名字
args表示給調用對象以元組的形式提供參數,比如target是函數a,他有兩個參數m,n,那麼該參數為args=(m, n)即可
kwargs表示調用對象的字典
name是別名,相當於給這個進程取一個名字
先來個小例子:
# -*- coding:utf-8 -*-
from multiprocessing import Process, Pool
import os
import time
def run_proc(wTime):
n = 0
while n < 3:
print "subProcess %s run," % os.getpid(), "{0}".format(time.ctime()) #獲取當前進程號和正在運行是的時間
time.sleep(wTime) #等待(休眠)
n += 1
if __name__ == "__main__":
p = Process(target=run_proc, args=(2,)) #申請子進程
p.start() #運行進程
print "Parent process run. subProcess is ", p.pid
print "Parent process end,{0}".format(time.ctime())
運行結果:
Parent process run. subProcess is 30196
Parent process end,Mon Mar 27 11:20:21 2017
subProcess 30196 run, Mon Mar 27 11:20:21 2017
subProcess 30196 run, Mon Mar 27 11:20:23 2017
subProcess 30196 run, Mon Mar 27 11:20:25 2017
根據運行結果可知,父進程運行結束後子進程仍然還在運行,這可能造成僵屍( zombie)進程。
通常情況下,當子進程終結時,它會通知父進程,清空自己所佔據的內存,並在內核里留下自己的退出信息。父進程在得知子進程終結時,會從內核中取出子進程的退出信息。但是,如果父進程早於子進程終結,這可能造成子進程的退出信息滯留在內核中,子進程成為僵屍(zombie)進程。當大量僵屍進程積累時,內存空間會被擠占。
有什麼辦法可以避免僵屍進程呢?
這里介紹進程的一個屬性 deamon,當其值為TRUE時,其父進程結束,該進程也直接終止運行(即使還沒運行完)。
所以給上面的程序加上p.deamon = true,看看效果。
# -*- coding:utf-8 -*-
from multiprocessing import Process, Pool
import os
import time
def run_proc(wTime):
n = 0
while n < 3:
print "subProcess %s run," % os.getpid(), "{0}".format(time.ctime())
time.sleep(wTime)
n += 1
if __name__ == "__main__":
p = Process(target=run_proc, args=(2,))
p.daemon = True #加入daemon
p.start()
print "Parent process run. subProcess is ", p.pid
print "Parent process end,{0}".format(time.ctime())
執行結果:
Parent process run. subProcess is 31856
Parent process end,Mon Mar 27 11:40:10 2017
這是問題又來了,子進程並沒有執行完,這不是所期望的結果。有沒辦法將子進程執行完後才讓父進程結束呢?
這里引入p.join()方法,它使子進程執行結束後,父進程才執行之後的代碼
# -*- coding:utf-8 -*-
from multiprocessing import Process, Pool
import os
import time
def run_proc(wTime):
n = 0
while n < 3:
print "subProcess %s run," % os.getpid(), "{0}".format(time.ctime())
time.sleep(wTime)
n += 1
if __name__ == "__main__":
p = Process(target=run_proc, args=(2,))
p.daemon = True
p.start()
p.join() #加入join方法
print "Parent process run. subProcess is ", p.pid
print "Parent process end,{0}".format(time.ctime())
執行結果:
subProcess 32076 run, Mon Mar 27 11:46:07 2017
subProcess 32076 run, Mon Mar 27 11:46:09 2017
subProcess 32076 run, Mon Mar 27 11:46:11 2017
Parent process run. subProcess is 32076
Parent process end,Mon Mar 27 11:46:13 2017
這樣所有的進程就能順利的執行了。
5. 如何使用Python實現多進程編程
1.Process
創建進程的類:Process([group[,target[,name[,args[,kwargs]]]]]),target表示調用對象,args表示調用對象的位置參數元組。kwargs表示調用對象的字典。name為別名。group實質上不使用。
方法:is_alive()、join([timeout])、run()、start()、terminate()。其中,Process以start()啟動某個進程。
屬性:authkey、daemon(要通過start()設置)、exitcode(進程在運行時為None、如果為–N,表示被信號N結束)、name、pid。其中daemon是父進程終止後自動終止,且自己不能產生新進程,必須在start()之前設置。
例1.1:創建函數並將其作為單個進程
importmultiprocessing
importtime
defworker(interval):
n=5
whilen>0:
print("Thetimeis{0}".format(time.ctime()))
time.sleep(interval)
n-=1
if__name__=="__main__":
p=multiprocessing.Process(target=worker,args=(3,))
p.start()
print"p.pid:",p.pid
print"p.name:",p.name
print"p.is_alive:",p.is_alive()
結果
12345678p.pid:8736p.name:Process-1p.is_alive:TrueThetimeisTueApr2120:55:122015ThetimeisTueApr2120:55:152015ThetimeisTueApr2120:55:182015ThetimeisTueApr2120:55:212015ThetimeisTueApr2120:55:242015
例1.2:創建函數並將其作為多個進程
importmultiprocessing
importtime
defworker_1(interval):
print"worker_1"
time.sleep(interval)
print"endworker_1"
defworker_2(interval):
print"worker_2"
time.sleep(interval)
print"endworker_2"
defworker_3(interval):
print"worker_3"
time.sleep(interval)
print"endworker_3"
if__name__=="__main__":
p1=multiprocessing.Process(target=worker_1,args=(2,))
p2=multiprocessing.Process(target=worker_2,args=(3,))
p3=multiprocessing.Process(target=worker_3,args=(4,))
p1.start()
p2.start()
p3.start()
print("ThenumberofCPUis:"+str(multiprocessing.cpu_count()))
forpinmultiprocessing.active_children():
print("childp.name:"+p.name+" p.id"+str(p.pid))
print"END!!!!!!!!!!!!!!!!!"
結果
1234567891011ThenumberofCPUis:4childp.name:Process-3p.id7992childp.name:Process-2p.id4204childp.name:Process-1p.id6380END!!!!!!!!!!!!!!!!!worker_1worker_3worker_2endworker_1endworker_2endworker_3
例1.3:將進程定義為類
importmultiprocessing
importtime
classClockProcess(multiprocessing.Process):
def__init__(self,interval):
multiprocessing.Process.__init__(self)
self.interval=interval
defrun(self):
n=5
whilen>0:
print("thetimeis{0}".format(time.ctime()))
time.sleep(self.interval)
n-=1
if__name__=='__main__':
p=ClockProcess(3)
p.start()
註:進程p調用start()時,自動調用run()
結果
12345thetimeisTueApr2120:31:302015thetimeisTueApr2120:31:332015thetimeisTueApr2120:31:362015thetimeisTueApr2120:31:392015thetimeisTueApr2120:31:422015
6. 一個for循環的Python腳本程序中如何加入多進程(並發進程)呢,急急急,在線等
#下面是一個示例,我寫了一個簡單的for循環,並加入了多線程並發。
#-*-coding:utf-8-*-
importthread,threading
#TestFunction
defForTest():
foriinrange(10):
printi
classmythread(threading.Thread):
def__init__(self,threadname):
threading.Thread.__init__(self)
defrun(self):
lock.acquire()
forjinxrange(int(times)):
#AddOwnFuctionHere
ForTest()
lock.release()
defMutiThread(num,times):
threads=[]
globalft
forxinxrange(num):
threads.append(mythread(num))
fortinthreads:
lock.acquire()
t.start()
lock.release()
fortinthreads:
t.join()
if__name__=='__main__':
globalnum,times,lock
num=2#num並發數
times=2#times運行次數
lock=threading.Lock()
MutiThread(num,times)
運行結果:
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9