python用进程和线程写抢票程序
时间: 2024-05-05 10:21:20 浏览: 9
Python可以使用多进程或多线程实现抢票程序。以下是使用进程和线程的示例:
使用进程实现抢票程序:
```python
import multiprocessing
import time
def buy_ticket(lock, num):
lock.acquire() # 加锁
if num > 0:
print("第{}个进程,抢到一张票!".format(multiprocessing.current_process().name))
num -= 1
else:
print("第{}个进程,票已售完!".format(multiprocessing.current_process().name))
lock.release() # 释放锁
if __name__ == '__main__':
num = 10 # 假设有10张票
lock = multiprocessing.Lock() # 创建锁
processes = []
for i in range(5): # 创建5个进程
p = multiprocessing.Process(target=buy_ticket, args=(lock, num))
processes.append(p)
p.start()
for p in processes:
p.join() # 等待所有进程结束
```
使用线程实现抢票程序:
```python
import threading
import time
def buy_ticket(lock, num):
lock.acquire() # 加锁
if num > 0:
print("第{}个线程,抢到一张票!".format(threading.current_thread().name))
num -= 1
else:
print("第{}个线程,票已售完!".format(threading.current_thread().name))
lock.release() # 释放锁
if __name__ == '__main__':
num = 10 # 假设有10张票
lock = threading.Lock() # 创建锁
threads = []
for i in range(5): # 创建5个线程
t = threading.Thread(target=buy_ticket, args=(lock, num))
threads.append(t)
t.start()
for t in threads:
t.join() # 等待所有线程结束
```
以上两个示例都使用了锁来保证多个进程或线程修改共享变量(票数)时的互斥性。使用进程或线程取决于具体的应用场景和需求。