進程間通信的4種方式


python提供了4種方式來滿足進程間的數據通信

1. 使用multiprocessing.Queue可以在進程間通信,但不能在Pool池創建的進程間進行通信

2. 使用multiprocessing.Manager.Queue可以在Pool進程池創建的進程間進行通信

3. 通過Pipe進行線程間的通信, pipe進程間通信的性能高於Queue,但是它只能在兩個進程間進行通信

4. 使用Manager類提供的數據結構可以進行進程間的通信

 

from multiprocessing import Process, Queue, Pool, Manager, Pipe
# 注意線程間的通信,使用的queue.Queue
# from  queue import Queue
import time


# 1. 使用multiprocessing.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)
#     p = Process(target=producer, args=(queue,))
#     c = Process(target=consumer, args=(queue,))
#     p.start()
#     c.start()
#     p.join()
#     c.join()


# 2. 使用共享全局變量,在多進程間通信(結論: 不行)
# def producer(a):
#     a += 1
#     time.sleep(2)
#
#
# def consumer(a):
#     time.sleep(2)
#     print(a)
#
# if __name__ == '__main__':
#     a = 1
#     p = Process(target=producer, args=(a,))
#     c = Process(target=consumer, args=(a,))
#     p.start()
#     c.start()
#     p.join()
#     c.join()


# 3. multiprocessing.Queue不能用於multiprocessing.Pool進程池創建的進程間進行通信
# def producer(queue):
#     queue.put('A')
#     time.sleep(2)
#
#
# def consumer(queue):
#     time.sleep(2)
#     data = queue.get()
#     print("consumer:%s" % data)
#
#
# if __name__ == '__main__':
#     # queue = Queue(10)  # 這個是使用multiprocessing.Queue,無效
#     queue = Manager().Queue(10)  # 這個是使用multiprocessing.Manager.Queue, 可以
#     pool = Pool(2)
#     pool.apply_async(producer, args=(queue,))
#     pool.apply_async(consumer, args=(queue,))
#     pool.close()
#     pool.join()


# 4.通過Pipe進行線程間的通信,  pipe進程間通信的性能高於Queue
# def producer(pipe):
#     pipe.send('admin')
#
#
# def consumer(pipe):
#     data = pipe.recv()
#     print("consumer:%s" % data)
#
#
# if __name__ == '__main__':
#     receive_pipe, send_pipe = Pipe()
#     """Pipe只能適應於兩個進程間的通信"""
#     p = Process(target=producer, args=(send_pipe,))
#     c = Process(target=consumer, args=(receive_pipe,))
#     p.start()
#     c.start()
#     p.join()
#     c.join()


# 5. 進程間通信的其它方式

def add_data(p_dict, key, value):
    p_dict[key] = value


if __name__ == '__main__':
    progress_dict = Manager().dict()  #Manager()類中提供的數據結構都能夠做到進程的通信
    first_progress = Process(target=add_data, args=(progress_dict, 'name', 'admin',))
    second_progress = Process(target=add_data, args=(progress_dict, 'age', 45,))
    first_progress.start()
    second_progress.start()
    first_progress.join()
    second_progress.join()
    print(progress_dict) #{'age': 45, 'name': 'admin'}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM