table of Contents
IPC
(Inter-Process Communication)
Spatial multiplexing memory is isolated from multiple processes can not interact directly
IPC refers to the inter-process communication
Method to realize :
1. Create a shared file
缺点: 效率较低
优点: 理论上交换的数据量可以非常大
适用于: 交互不频繁 且数据量较大的情况
2. Shared Memory (main mode)
缺点: 数据量不能太大
优点: 效率高
适用于: 交互频繁,但是数据量小
3. Pipeline
管道也是基于文件的 它是单向的 编程比较复杂
4.socket
编程复杂,更适用于基于网络来交换数据
The first way of shared memory
- Manger does not write files to achieve grab votes
We can create a container for inter-process synchronization, but does not address security issues, it is not commonly used
from multiprocessing import Process, Lock, Manager
def show(ticket):
'''查票'''
print(ticket)
print('当前剩余票数', ticket['count'])
def buy(ticket):
'''买票'''
print(ticket)
count = ticket['count']
if count > 0:
count -= 1
ticket['count'] = count
print('抢票成功')
else:
print('没有票')
def task(lock, ticket):
# print(ticket)
show(ticket)
lock.acquire() # 安全问题需要自己另外加锁
buy(ticket)
lock.release()
if __name__ == '__main__':
ticket = {'count': 1}
m = Manager()
sync_ticket = m.dict(ticket)
lock = Lock()
ps = []
for i in range(5):
p = Process(target=task, args=(lock, sync_ticket))
p.start()
ps.append(p)
for p in ps: # 必须要用join(),否则传入子进程的不是字典,不知道为什么
p.join()
Note: You must use the join (), otherwise passed in the child process is not a dictionary, and the reason is not clear
Queue
Queue Queue is translated into a special container so special is that the access order of FIFO
It can help us to complete inter-process communication
from multiprocessing import Queue
q = Queue(2) # 创建队列 并且同时只能存储2个元素
q.put(1)
q.put(2)
# q.put(3,block=True,timeout=3) # 默认是阻塞的 当容器中没有位置了就阻塞 直到有人从里面取走元素为止
# block:是否阻塞,默认是True,如果为False就不会阻塞,但是满了会报错
# timeout:阻塞等待的时间,超出就不阻塞
print(q.get())
print(q.get())
print(q.get(block=True,timeout=3))
Extended: Stack
Is a special container that particular access order is last out
Function call stack
Function call stack when calling function
Function call function execution end pop