I have a Flask API where every time a POST request is sent to a specific URL, the job is put on a thread to run in parallel so that my request can continue its work. However, if a user sends multiple POST requests, the function will start the same jobs on several threads and I don't want that. I want only one thread to run and if other requests comes, I want it to send a message to the user saying a thread is already running instead of joining the thread. For that to happen, I need to check if the Thread is still alive and then execute my code. But I am having issues with that.
I achieved the following:
# [POST] Post a tweet in database
@jwt_required
def post(self):
# Get json body from post request
body = request.get_json()
# Verify body format
try:
# Checks data
value = body["value_flag"]
if value == "start_live_tweet_streaming":
stream = Coroutine.Thread(target=self.__twitterInstantiation)
stream.start()
if stream.is_alive():
print("Thread still running")
else:
return Err.ERROR_FLAG_INCORRECT
except Exception as e:
return Err.ERROR_JSON_FORMAT_INCORRECT
return Succ.SUCCESS_TWEETS_STARTED
My code never reaches the line print("Thread still running")
because every time it enters the POST request function a new thread is created here stream = Coroutine.Thread(target=self.__twitterInstantiation)
and therefore cannot see if the old one is alive.
Can someone please help me here ?
To get all the alive threads, you can use threading.enumerate()
.
Every Thread
can have a custom name. It is obtainable via the name
property.
If you give a thread the name that indicates the job, you can get the thread's name and prevent spawning of the same operation.
if value == "start_live_tweet_streaming":
for th in threading.enumerate():
if th.name == job_name:
print("Thread still running")
break
else:
print("Starting a new job thread")
stream = Coroutine.Thread(target=self.__twitterInstantiation, name=job_name)
stream.start()