import multiprocessing
import time
class
classprocess
(multiprocessing.process)
:def
run(self)
: n =
5while n >0:
print
(n) time.sleep(3)
n -=
1if __name__ ==
'__main__'
: p = classprocess(
) p.start(
) p.join()》
5432
1
close()
: 關閉pool, 使其不再接受新的任務;
terminate()
: 不管任務是否完成, ⽴即終⽌;
join()
: 主程序阻塞, 等待⼦程序的退出, 必須在close或terminate之後使⽤;
from multiprocessing import pool
import random, time
defrun
(num)
:print
(random.random(
)* num)
time.sleep(2)
if __name__ ==
'__main__'
: po = pool(3)
# 定義乙個程序池,最大程序數為3,預設大小為cpu核數
for i in
range(10
):(i,)
) po.close(
)# 程序池關閉之後不再接收新的請求
po.join(
)# 等待 po 中所有子程序結束,必須放在close後面
》0.0
0.8301966976322728
1.596830911310102
1.3007124340938216
3.723402769957984
4.410041843936074
0.5191815870872576
4.590799783059167
7.273749114887141
4.145621686302077
python多程序建立
程序相當於是乙個工作車間,裡面可以有很多流水線 執行緒 使用multiprocessing來建立程序物件。如下 import multiprocessing num 0def add1 n global num for i in range n num 1print num defadd2 n gl...
Python多程序 實現多程序的幾種方式
coding utf 8 pid os.fork 1.只用在unix系統中有效,windows系統中無效 2.fork函式呼叫一次,返回兩次 在父程序中返回值為子程序id,在子程序中返回值為0 import os pid os.fork if pid 0 print 執行子程序,子程序pid 父程序...
python 多程序的兩種建立方式
python中使用執行緒有兩種方式 函式或者用類來包裝執行緒物件。第一種 函式 import time import threading defcoding for x in range 3 print 正在寫 s threading.current thread 獲取程序名字 time.sleep...