python endpoint starting a thread with locking

Viewed 932

I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this:

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.")

So, when the job gets started, a thread will be created using the method job:

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

So far so good, the endpoint is working, starts a job and locks as long as the job is running. But my problem is that the thread is still alive although the job "finished" and released the lock. I was hoping that the thread would close itself after execution. Maybe the problem is that myapp is keeping it alive? How can I stop it?

1 Answers

I figured out this kind of solution:

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
Related