python多进程编程-多进程编程中的IPC(三)
2023-06-13 09:18:44 时间
消息队列
消息队列是一种进程间通信方式,可以实现进程之间的异步通信,即一个进程向消息队列发送消息,另一个进程从消息队列中接收消息。在Python中,可以使用multiprocessing模块中的Queue类来创建消息队列。
下面是一个使用消息队列实现多进程通信的示例代码:
import multiprocessing
def sender(queue):
queue.put('hello')
def receiver(queue):
msg = queue.get()
print('received:', msg)
if __name__ == '__main__':
queue = multiprocessing.Queue()
p1 = multiprocessing.Process(target=sender, args=(queue,))
p2 = multiprocessing.Process(target=receiver, args=(queue,))
p1.start()
p2.start()
p1.join()
p2.join()
这里我们定义了两个进程函数sender和receiver,分别用于向消息队列发送消息和从消息队列中接收消息。在主程序中,我们创建了一个消息队列queue,并使用multiprocessing.Queue()函数将其创建出来。然后创建了两个进程p1和p2,分别将sender和receiver函数作为进程的执行函数。在进程p1中,我们向消息队列queue中发送了一条消息“hello”;在进程p2中,我们从消息队列queue中接收了这条消息,并打印出来。
相关文章
- Python-基础05-字符编码
- python中关于命名的例子_Python 命名规范入门实例「建议收藏」
- Python udp编程_python socket udp
- python chmod_Python os.chmod用法及代码示例
- Python 基础篇(三)
- Python通过SNMP监控网络设备
- python多进程编程-进程之间的关系
- Python使用platform库获取系统信息:操作系统信息、硬件信息、python环境信息
- Python抓妹子图+多进程详解编程语言
- python全栈开发-Day9 函数对象、函数嵌套、名称空间与作用域(装饰器基础)详解编程语言
- Python学习:6.python内置函数详解编程语言
- 使用Python编程连接MySQL数据库(python连mysql)
- 用Python仿写MSSQL 编程体验更有趣(python仿mssql)
- 用Python和MD5实现网站挂马检测程序
- Python读写Excel文件方法介绍