1.python 中創(chuàng)建進程的兩種方式:
from multiprocessing import Process
import time
def test_():
print '-----test-----'
if __name__ == '__main__':
p = Process(target=test_)
p.start()
while True:
print '--main--'
'''1.通過process 類創(chuàng)建一個進程對象,然后start即可開啟進程, test
test_函數(shù)是進程實現(xiàn)的功能'''
from multiprocessing import Process
import time
class MyNewProcess(Process):
def run(self):
print '------run-------'
if __name__ == '__main__':
p = MyNewProcess()
p.start()
print '---main-----'
'''2.通過類似繼承process 子類中必須有run 方法 里邊實現(xiàn) 進程功能
創(chuàng)建對象之后 調用start'''
2.進程池
from multiprocessing import Pool
from time import sleep
import os
def func(num):
for i in range(3):
print '%s %s' %(os.getpid(),num) #
sleep(2)
def main():
pool = Pool(3)
for i in range(3, 6):
res = pool.apply_async(func, (i,))
pool.close()
pool.join()
if __name__ == '__main__':
main()
3.進程間通信
'''python 進程間通信 Queue '''
'''1.Queue使用方法
1.Queue.qsize(): 返回當前隊列包含的消息數(shù)量
2.Queue.empty(): 如果隊列為空 返回True 反之 False
3.Queue.full(): 如果隊列滿了返回True 反之 False
4.Queue.get(): 獲取隊列中一條消息 然后將其從隊列中移除 可傳參數(shù) 超市時長
Queue.get_nowait(): 相當于 Queue.get(False) 取不到值 觸發(fā)異常
Queue.put(): 將一個值添加到數(shù)列 可傳參數(shù) 超時時長
Queue.put_nowait():相當于 Queue.get(False) 當隊列滿時 報錯
'''
from multiprocessing import Process, Queue
import time
q = Queue() # 創(chuàng)建隊列
for i in range(10):
q.put(i)
def test_a():
try:
while True:
num = q.get_nowait()
print '我是進程a 取出數(shù)字為:%s'%num
time.sleep(1)
except Exception, e:
print e
def test_b():
try:
while True:
num = q.get_nowait()
print '我是進程b 取出數(shù)字是:%s'%num
time.sleep(1)
except Exception, e:
print e
if __name__ == '__main__':
p1 = Process(target=test_a)
p2 = Process(target=test_b)
p1.start()
p2.start()
至此 簡單得使用已經(jīng)結束
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

