#多程序呼叫(大部分與多執行緒的操作一樣)
#呼叫方式1
from multiprocessing import
process
import
time
deff(name):
time.sleep(1)
print('
hello
', name, time.ctime())
if__name__ == '
__main__':
p_list =
for i in range(3):
p = process(target=f, args=('
alex
',))
p.start()
for i in
p_list:
i.join()
print('
end')#
呼叫方式2
from multiprocessing import
process
import
time
class
myprocess(process):
#def __init__(self):
#super(myprocess, self).__init__()
#self.name = name
defrun(self):
time.sleep(1)
print('
hello
', self.name, time.ctime())
if__name__ == '
__main__':
p_list =
for i in range(3):
p =myprocess()
#p.daemon = true # 設定守護程序
p.start()
#for i in p_list:
#i.join()
print('
end...')
#檢視程序的pid
from multiprocessing import
process
import
os, time
definfo(title):
print('
title:
', title)
print('
parent process:
', os.getppid())
print('
process id:
', os.getpid())
deff(name):
info(
'function f')
print('
hello
', name)
if__name__ == '
__main__':
info(
'main process line')
time.sleep(1)
print('
-' * 30)
p = process(target=info, args=('
alex
',))
p.start()
p.join()
#title: main process line
#parent process: 1792 # 父程序的程序pid(pycharm)
#process id: 4116 # 當前.py檔案執行的pid
#------------------------------
#title: alex
#parent process: 4116 # 父程序的pid即當前.py檔案執行的pid
#process id: 6392 # 產生的子程序的pid
#process類的方法與屬性
#構造方法:
#process(group[, target[, name[, args[, kwargs]]]])
#group: 執行緒組,目前還沒有實現,庫引用中提示必須是none
#target: 要執行的方法
#name: 指定程序名
#args / kwargs: 要傳入方法的引數##
例項方法:
#is_alive() 返回程序是否在執行
#join([timeout]) 阻塞當前上下文環境的程序,直到呼叫此方法的程序終止或到達指定的timeout
#start() 進行準備就緒,等待cpu排程
#run() start()方法呼叫run方法,如果例項程序時未制定傳入target,這start執行預設run方法
#terminate() 不管任務是否完成,立即停止工作程序##
屬性:#
daemon 和執行緒的setdaemon功能一樣
#name 程序名字
#pid 程序號
from multiprocessing import
process
import
time
class
myprocess(process):
def__init__
(self, num):
super(myprocess, self).
__init__
() self.num =num
defrun(self):
time.sleep(1)
(self.is_alive(), self.num, self.pid)
time.sleep(1)
if__name__ == '
__main__':
p_list =
for i in range(10):
p =myprocess(i)
for p in
p_list:
p.start()
print('
main process end
')
程序(一) 多程序的呼叫
由於gil的存在,python中的多執行緒其實並不是真正意義的多執行緒,如果想要充分地使用多核cpu的資源,在python中大部分情況需要使用多程序。multiprocessing包是python中的多程序管理包。與threading.thread類似,他利用multiprocessing.proc...
多程序 多程序queue
多程序 import multiprocessing import threading import time defthread run print threading.get ident defrun name time.sleep 2 print hello name t threading....
python多程序 python多程序
當有多個非相關任務需要處理時,並行能大大提高處理速度。這裡簡要介紹python的multiprocessing模組。簡單多程序編寫 當我們任務數量確定而且比較少的時候,可以手動為每個任務指定乙個程序來執行。import multiprocessing as mp def f a print a if...