1.python 中創(chuàng)建進(jìn)程的兩種方式:
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)建一個(gè)進(jìn)程對象,然后start即可開啟進(jìn)程, test test_函數(shù)是進(jìn)程實(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 方法 里邊實(shí)現(xiàn) 進(jìn)程功能 創(chuàng)建對象之后 調(diào)用start'''
2.進(jìn)程池
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.進(jìn)程間通信
'''python 進(jìn)程間通信 Queue ''' '''1.Queue使用方法 1.Queue.qsize(): 返回當(dāng)前隊(duì)列包含的消息數(shù)量 2.Queue.empty(): 如果隊(duì)列為空 返回True 反之 False 3.Queue.full(): 如果隊(duì)列滿了返回True 反之 False 4.Queue.get(): 獲取隊(duì)列中一條消息 然后將其從隊(duì)列中移除 可傳參數(shù) 超市時(shí)長 Queue.get_nowait(): 相當(dāng)于 Queue.get(False) 取不到值 觸發(fā)異常 Queue.put(): 將一個(gè)值添加到數(shù)列 可傳參數(shù) 超時(shí)時(shí)長 Queue.put_nowait():相當(dāng)于 Queue.get(False) 當(dāng)隊(duì)列滿時(shí) 報(bào)錯(cuò) ''' from multiprocessing import Process, Queue import time q = Queue() # 創(chuàng)建隊(duì)列 for i in range(10): q.put(i) def test_a(): try: while True: num = q.get_nowait() print '我是進(jìn)程a 取出數(shù)字為:%s'%num time.sleep(1) except Exception, e: print e def test_b(): try: while True: num = q.get_nowait() print '我是進(jìn)程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)結(jié)束
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
