用代码实现并发式会议类程序
时间: 2024-05-01 14:19:04 浏览: 78
以下是一个简单的并发式会议类程序的实现,它允许多个参与者同时加入会议并进行交流:
```python
import threading
class Conference:
def __init__(self):
self.participants = []
def join(self, participant):
self.participants.append(participant)
print(f'{participant} joined the conference.')
def leave(self, participant):
self.participants.remove(participant)
print(f'{participant} left the conference.')
def broadcast(self, sender, message):
for participant in self.participants:
if participant != sender:
participant.receive(sender, message)
class Participant:
def __init__(self, name, conference):
self.name = name
self.conference = conference
def join_conference(self):
self.conference.join(self)
def leave_conference(self):
self.conference.leave(self)
def send_message(self, message):
self.conference.broadcast(self, message)
def receive(self, sender, message):
print(f'{self.name} received a message from {sender.name}: {message}')
if __name__ == '__main__':
conference = Conference()
alice = Participant('Alice', conference)
bob = Participant('Bob', conference)
alice.join_conference()
bob.join_conference()
alice.send_message('Hi, Bob!')
bob.send_message('Hello, Alice!')
alice.leave_conference()
bob.leave_conference()
```
在这个程序中,Conference 类维护了一个参与者列表,可以通过 join() 和 leave() 方法添加和删除参与者。broadcast() 方法可以向所有参与者广播消息。Participant 类表示一个参与者,具有 join_conference()、leave_conference()、send_message() 和 receive() 方法,用于加入会议、离开会议、发送消息和接收消息。在这个示例程序中,alice 和 bob 分别加入了会议并互相发送了几条消息,最后离开了会议。