python 多程序的通訊,介紹與使用

2021-08-28 08:38:23 字數 2455 閱讀 2388

import time

from multiprocessing import process,queue #要用multiprocessing下面的queue才可以。同樣這個也不能用於多執行緒通訊

#from queue import queue #這個是用於多程序的,並不可以用 會報錯

# def producer(queue):

# queue.put("a")

# time.sleep(2)

## def consumer(queue):

# time.sleep(2)

# data = queue.get()

# print(data)

## if __name__ == "__main__":

# queue = queue(10)

# my_producer = process(target=producer, args=(queue,))

# my_consumer = process(target=consumer, args=(queue,))

# my_producer.start()

# my_consumer.start()

# my_producer.join()

# my_consumer.join()

from multiprocessing import manager

#multiprocessing中的queue不能用於pool程序池

#pool中的程序間通訊需要使用manager中的queue

# def producer(queue):

# queue.put("a")

# time.sleep(2)

## def consumer(queue):

# time.sleep(2)

# data = queue.get()

# print(data)

## if __name__ == "__main__":

# queue = manager().queue(10)

# pool = pool(2)##

# pool.close()

# pool.join()

from multiprocessing import pipe

#通過pipe實現程序間通訊

#pipe的效能高於queue

# def producer(pipe):

# pipe.send("bobby")

## def consumer(pipe):

# print(pipe.recv())

## if __name__ == "__main__":

# recevie_pipe, send_pipe = pipe()

# #pipe只能適用於兩個程序

# my_producer= process(target=producer, args=(send_pipe, ))

# my_consumer = process(target=consumer, args=(recevie_pipe,))

## my_producer.start()

# my_consumer.start()

# my_producer.join()

# my_consumer.join()

#如果想要實現,像執行緒一樣共同去維護乙個變數,可以用manager下的資料型別

from multiprocessing import process, manager

def add_data(p_dict, key, value):

p_dict[key] = value #這裡實際操作的時候也要注意加lock, manager下也是有lock的

if __name__ == "__main__":

progress_dict = manager().dict()

first_progress = process(target=add_data, args=(progress_dict, "bobby1", 22))

second_progress = process(target=add_data, args=(progress_dict, "bobby2", 23))

first_progress.start()

second_progress.start()

first_progress.join()

second_progress.join()

print(progress_dict)

python多程序通訊

這是看書筆記 python提供了多種程序通訊的方式,比如說queue,pipe,value array等。其中queue主要用來在多個程序之間實現通訊。pipe常用來在兩個程序之間實現通訊。queue是多程序安全佇列,queue通過put和get方法來實現多程序之間的資料傳遞。put方法用於將資料插...

python多程序通訊

python 多程序實現 from multiprocessing import import time import os class clockprocess process def init self,interval self.interval interval process.init s...

Python 多程序 通訊

1.多程序佇列 只能實現資料互動,不能共享 from multiprocessing import process,queue import time import uuid class myprocess process def init self,q super myprocess,self i...