python 进程间通信

队列Queue模块

管道:subprocess 

stdin stdout stderr

队列:先进先出 自动带锁(暂时未理解)

堆栈:先进后出

队列在多进程的时候不精准

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from multiprocessing import Queue
q = Queue(3)
 
q.put(1111)
q.put(2222)
q.full()
q.put(3333)
# q.put(4444)  # 只能放3个数据,放了4个数据也会阻塞
 
 
q1 = q.get()
q2 = q.get()
q3 = q.get()
q.empty()
# q4 = q.get()   # 没有数据就会阻塞,等在那里取数据
# q5 = q.get()
print(q1,q2,q3,)
try:
    q4 = q.get()
    print(q4)
except Exception as e:
    print("no data")

 借助队列实现进程与进程之间的通信

一、主进程同子进程之间的通信

from multiprocessing import Process, Queue
def producer(q):
q.put("hello world")

if __name__ == "__main__":
q = Queue()
p = Process(target=producer, args=(q,))
p.start()
print(q.get())
二、子进程与子进程之间的通信
from multiprocessing import Process, Queue

def producer(q):
q.put("hello world")

def customer(q):

print(q.get())

if __name__ == "__main__":
q = Queue()
p1 = Process(target=producer, args=(q,))
p2 = Process(target=customer, args=(q,))
p1.start()
p2.start()

 

posted @   禾火123  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示