两个.py文件的多进程通信举例
时间: 2024-05-04 16:20:38 浏览: 19
假设有两个.py文件,一个为`sender.py`,另一个为`receiver.py`,我们需要让这两个文件进行多进程通信。
**sender.py**
```python
import multiprocessing
def send_message(conn):
message = "Hello, receiver!"
conn.send(message)
if __name__ == '__main__':
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=send_message, args=(child_conn,))
p.start()
p.join()
print(f"Sent message: {parent_conn.recv()}")
```
**receiver.py**
```python
import multiprocessing
def receive_message(conn):
message = conn.recv()
print(f"Received message: {message}")
if __name__ == '__main__':
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=receive_message, args=(parent_conn,))
p.start()
p.join()
child_conn.send("Hello, sender!")
```
在`sender.py`中,我们定义了一个函数`send_message`,该函数将消息发送到`child_conn`管道中。然后,我们使用`multiprocessing.Process`创建一个新的进程,并将`child_conn`作为参数传递给该新进程。该新进程将运行`send_message`函数。
在`receiver.py`中,我们定义了一个函数`receive_message`,该函数将从`parent_conn`管道中接收消息并打印出来。然后,我们使用`multiprocessing.Process`创建一个新的进程,并将`parent_conn`作为参数传递给该新进程。该新进程将运行`receive_message`函数。
在两个文件中,我们使用`multiprocessing.Pipe`创建了一个双向管道,该管道将用于多进程通信。在`sender.py`中,我们将`child_conn`发送给新进程,而在`receiver.py`中,我们将`parent_conn`发送给新进程。
最后,我们在`sender.py`中使用`parent_conn.recv()`接收从`receiver.py`发送的消息,并打印出来。在`receiver.py`中,我们使用`child_conn.send()`将消息发送给`sender.py`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)