如何确保只有一个进程在线程中运行

2024-04-20 10:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类型为coroutine的类方法,从一个用户那里同时得到多个对它的请求,假设用户在t=0时调用一个函数,函数需要10毫秒进行处理,用户在t=3毫秒时再次异步调用,然后在t=10毫秒时响应reuest 1,在t=20毫秒时响应请求2,那么请求2的时间大约是17毫秒,但是我想看下面的场景

如果请求1在t=0毫秒时来自一个用户,并且在请求2在t=3毫秒时进入之前运行了3毫秒,则必须销毁调用1并启动调用响应2,并且对请求2的响应必须在t=13毫秒时返回,周转时间为10毫秒

类似于确保每个用户运行一个进程。 如果有一个函数

  def Myfunction(a,b):
     return a+b

  #user calls
  #at t = 0
  myfunction(10,5) #takes 10 ms

  #at t=3 
  myfunction(100,200)#takes 10 ms

  so  i want that myfunction must have only single/latest call  instance running  for each user i.e in above case only myfunction(100,200) my be occupying the the CPU after t=3 .

我正在使用python异步库并从语句和事件循环中生成。你知道吗

请提供一些如何实现上述想法的想法。你知道吗


Tags: the方法函数用户类型only时间场景
1条回答
网友
1楼 · 发布于 2024-04-20 10:36:01

在asyncio中,您将使用任务来处理这个问题。跟踪当前正在运行的函数,并在再次调用时取消它

_running = None
async def wrapped_myfunction():
    global _running
    if _running is not None:
        _running.cancel()
    _running = asyncio.create_task(myfunction())
    return await _running

相关问题 更多 >