MST

星途 面试题库

面试题:Go 函数与协程在复杂业务场景下的协作问题

假设你有一个电商系统,需要实现库存检查、价格计算、订单生成这三个操作,每个操作由一个函数实现,并且要求将这些函数作为协程并发执行,最后汇总结果完成订单流程。请描述实现思路,并编写关键代码,说明如何处理可能出现的竞争条件和数据同步问题。
45.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义函数:分别定义库存检查、价格计算、订单生成的函数。
  2. 协程并发执行:使用Python的asyncio库将这三个函数作为协程并发执行。
  3. 数据同步:通过asyncio的锁机制来处理竞争条件,确保数据的一致性。

关键代码

import asyncio


async def check_stock(product_id, quantity):
    # 模拟库存检查逻辑
    await asyncio.sleep(1)
    return True


async def calculate_price(product_id, quantity):
    # 模拟价格计算逻辑
    await asyncio.sleep(1)
    return 100 * quantity


async def generate_order(product_id, quantity, price):
    # 模拟订单生成逻辑
    await asyncio.sleep(1)
    print(f"Order for product {product_id} with quantity {quantity} and price {price} generated.")


async def main(product_id, quantity):
    stock_lock = asyncio.Lock()
    price_lock = asyncio.Lock()
    order_lock = asyncio.Lock()

    async def _check_stock():
        async with stock_lock:
            return await check_stock(product_id, quantity)

    async def _calculate_price():
        async with price_lock:
            return await calculate_price(product_id, quantity)

    async def _generate_order(price):
        async with order_lock:
            await generate_order(product_id, quantity, price)

    stock_task = asyncio.create_task(_check_stock())
    price_task = asyncio.create_task(_calculate_price())

    await asyncio.gather(stock_task, price_task)

    if stock_task.result():
        await _generate_order(price_task.result())


if __name__ == "__main__":
    product_id = 1
    quantity = 5
    asyncio.run(main(product_id, quantity))

竞争条件和数据同步处理

  1. 锁机制:在每个关键函数(库存检查、价格计算、订单生成)执行时,使用asyncio.Lock()创建锁对象。在进入关键操作前,通过async with语句获取锁,确保同一时间只有一个协程可以执行该操作,避免竞争条件。
  2. 任务管理:使用asyncio.create_task()创建协程任务,并通过asyncio.gather()等待所有相关任务完成,确保数据按顺序处理。