python端点启动一个带锁的线程

时间:2021-04-21 09:52:53

标签: python multithreading fastapi

我正在使用 FASTApi 并尝试实现一个端点,该端点可启动一项工作。一旦作业开始,端点将被“锁定”,直到前一个作业完成。到目前为止它是这样实现的:

myapp.lock = threading.Lock()

@myapp.get("/jobs")
def start_job(some_args):
    if myapp.lock.acquire(False):
        th = threading.Thread(target=job,kwargs=some_args)
        th.start()
        return "Job started"
    else:
        raise HTTPException(status_code=400,detail="Job already running.")

因此,当作业开始时,将使用方法 job 创建一个线程:

def job(some_args):
    try:
        #doing some stuff, creating objects and writing to files
    finally:
        myapp.lock.release()

到目前为止一切顺利,端点正在工作,只要作业正在运行,就会启动作业并锁定。 但我的问题是,尽管作业“完成”并释放了锁,但线程仍然存在。我希望线程在执行后会自行关闭。也许问题在于 myapp 让它保持活力?我怎样才能阻止它?

1 个答案:

答案 0 :(得分:0)

我想出了这种解决方案:

myapp.lock = False

@myapp.get("/jobs")
async def start_job(some_args, background_tasks: BackgroundTasks):
    if not myapp.lock:
        background_tasks.add_task(job, some_args)
        return "Job started"
    else:
        raise HTTPException(status_code=400,detail="Job already running.")

def job(some_args):
    try:
        myapp.lock = True
        #doing some stuff, creating objects and writing to files
    finally:
        myapp.lock = False