写一个CountDownLunch的排队取票的代码
时间: 2024-05-06 11:16:51 浏览: 15
以下是一个简单的 CountDownLunch 排队取票的代码示例:
```python
import threading
import time
class CountDownLunch:
def __init__(self, num_tickets):
self.num_tickets = num_tickets
self.tickets_sold = 0
self.lock = threading.Lock()
def buy_ticket(self):
with self.lock:
if self.tickets_sold < self.num_tickets:
self.tickets_sold += 1
print(f"Ticket {self.tickets_sold} sold!")
return True
else:
print("Sorry, all tickets have been sold out.")
return False
def queue_up(cd_lunch, num_people):
for i in range(num_people):
while not cd_lunch.buy_ticket():
time.sleep(0.1)
if __name__ == "__main__":
num_tickets = 10
num_people = 20
cd_lunch = CountDownLunch(num_tickets)
threads = []
for i in range(3):
t = threading.Thread(target=queue_up, args=(cd_lunch, num_people))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All tickets sold out!")
```
这个代码创建了一个 `CountDownLunch` 类,它记录了剩余票数和已售票数,并使用线程锁确保多个线程不会同时尝试购买同一张票。`queue_up` 函数代表一个人排队取票的过程,它会不断尝试购买票,直到购买成功为止。在主函数中,我们创建了3个线程,每个线程代表一组人排队取票,最终所有票都会售罄。