Python 抢购代码实现:模拟多用户争抢商品

本代码使用 Python 多线程模拟 10 个用户同时抢购商品,并通过锁机制确保商品数量的同步访问。代码简单易懂,适合初学者学习多线程编程和锁的使用。

import threading

# 假设商品数量为 10 个
goods_num = 10

# 定义一个锁
lock = threading.Lock()

# 定义一个抢购函数
def buy_goods(num):
    global goods_num
    # 加锁
    lock.acquire()
    if goods_num > 0:
        goods_num -= 1
        print('用户{}抢购成功,剩余商品数量为{}'.format(num, goods_num))
    else:
        print('用户{}抢购失败,商品已售罄'.format(num))
    # 释放锁
    lock.release()

# 定义 10 个线程,模拟 10 个用户同时抢购商品
threads = []
for i in range(1, 11):
    t = threading.Thread(target=buy_goods, args=(i,))
    threads.append(t)

# 启动线程
for t in threads:
    t.start()

# 等待所有线程结束
for t in threads:
    t.join()

说明:

  1. 代码中假设商品数量为 10 个;
  2. 定义了一个锁,用于保护共享资源(商品数量);
  3. 定义了一个抢购函数,该函数接受一个参数 num,表示用户编号;
  4. 在函数内部先加锁,然后判断商品数量是否大于 0,如果是,则减少商品数量,打印抢购成功的信息,否则打印抢购失败的信息;
  5. 最后释放锁;
  6. 定义了 10 个线程,模拟 10 个用户同时抢购商品;
  7. 启动线程,并等待所有线程结束。
Python 抢购代码实现:模拟多用户争抢商品

原文地址: https://www.cveoy.top/t/topic/lXb0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录