python中的程序池

2021-07-31 15:26:29 字數 1532 閱讀 7175

#coding: utf-8

import multiprocessing

import time

deffunc

(msg):

print

"msg:", msg

time.sleep(3)

print

"end"

if __name__ == "__main__":

pool = multiprocessing.pool(processes = 3)

for i in xrange(4):

msg = "hello %d" %(i)

print

"mark~ mark~ mark~~~~~~~~~~~~~~~~~~~~~~"

pool.close()

pool.join() #呼叫join之前,先呼叫close函式,否則會出錯。執行完close後不會有新的程序加入到pool,join函式等待所有子程序結束

print

"sub-process(es) done."

一次執行結果

mmsg: hark~ mark~ mark~~~~~~~~~~~~~~~~~~~~~~

msg: hello 0

msg: hello 1

msg: hello 2

endmsg: hello 3

endend

endsub-process(es) done.

例2:使用程序池(阻塞)

#coding: utf-8

import multiprocessing

import time

deffunc

(msg):

print

"msg:", msg

time.sleep(3)

print

"end"

if __name__ == "__main__":

pool = multiprocessing.pool(processes = 3)

for i in xrange(4):

msg = "hello %d" %(i)

print

"mark~ mark~ mark~~~~~~~~~~~~~~~~~~~~~~"

pool.close()

pool.join() #呼叫join之前,先呼叫close函式,否則會出錯。執行完close後不會有新的程序加入到pool,join函式等待所有子程序結束

print

"sub-process(es) done."

一次執行的結果

msg: hello 0

endmsg: hello 1

endmsg: hello 2

endmsg: hello 3

endmark~ mark~ mark~~~~~~~~~~~~~~~~~~~~~~

sub-process(es) done.

Python中的程序池

一喪 為了情人節和你出去,我有了好幾十萬自行車的使用權 我們先來說我們為什麼使用這個程序池。目的 可以節約大量的時間。既然這麼重要,那我們都應該使用什麼方法去呼叫方法呢?我們來看一下 pool是什麼?pool就是我們的程序池了,讓我們來看一下怎麼用這個方法 import multiprocessin...

python中的程序池

python中,程序池內部會維護乙個程序序列。當需要時,程式會去程序池中獲取乙個程序。如果程序池序列中沒有可供使用的程序,那麼程式就會等待,直到程序池中有可用程序為止。terminate 立刻關閉程序池 join 主程序等待所有子程序執行完畢,必須在close或terminete之後 close 等...

python 中的程序池

from multiprocessing import pool import time,random def jincheng i print s開始 i time.sleep random.random 加時間是為了體現多程序的併發效果 print s結束 i if name main p po...