在 Python 线程中检查线程是否仍然是 运行

Check if a thread is still running in Python Threading

我有一个 Flask API,每次 POST 请求被发送到特定的 URL,作业被并行地放在一个线程上 运行这样我的请求就可以继续工作。但是,如果用户发送多个 POST 请求,该函数将在多个线程上启动相同的作业,我不希望这样。我只希望一个线程 运行 并且如果其他请求到来,我希望它向用户发送一条消息说线程已经 运行ning 而不是加入线程。为此,我需要检查线程是否仍然存在,然后执行我的代码。但我对此有疑问。

我取得了以下成绩:

# [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

我的代码从未到达 print("Thread still running") 行,因为每次它进入 POST 请求函数时都会在此处创建一个新线程 stream = Coroutine.Thread(target=self.__twitterInstantiation) 因此无法查看旧线程是否存在.

有人可以帮我吗?

枚举活动线程

要获取所有活动线程,可以使用threading.enumerate()

线程名称

Thread can have a custom name. It is obtainable via the name 属性.

解决方案

如果您为线程指定了表明作业的名称,您可以获得线程的名称并防止产生相同的操作。

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()