在 Google Cloud 运行 上使用线程的 Python Flask 应用的性能不一致

Inconsistent performance of a Python Flask app using Threading on Google Cloud Run

我试图了解 Python Flask 应用程序在 Google 云 运行 上看似不一致的性能。该应用程序将图像文件作为输入,使用 cv2 进行一些预处理,然后使用 Tesseract 进行 OCR。我使用 Python 线程来并行化图像和 OCR 处理,但即便如此,整个处理过程仍可能需要 10 到 20 秒。

@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    processing_results = process_input_image(image_path)

    return processing_results

def process_input_image(image_path)
    # process_input_image uses Python Threads to parallelize image processing
    for work in list_of_image_processing_work:
        th = Thread(target=do_image_work, args=(work, results))
        th.start()
    # wait for all threads to complete
    return results

我想要 return 一个更直接的响应,表明处理需要更多时间。因此,我尝试了以下更改以在图像处理调用上启动一个线程。 Net,我正在启动一个线程来调用一个例程,该例程本身会启动一系列线程来进行图像处理。

@app.route('/process_image/<path:image_path>')
def process_image(image_path):
    th = Thread(target=process_input_image, args=(image_path, results))
    th.start()

    return 'This\'ll just be a moment or so.'

但是,一旦我添加了第二层线程,Google 云 运行 上的处理似乎就停止了。查看日志,我可以看到例程 process_input_image 开始,但进展似乎进展缓慢,几乎就像它的优先级很低,最终永远不会完成。我想知道这是否是线程优先级的事情。

当HTTP请求returns消息时,CPU处于空闲状态。这意味着线程 运行ning 在 HTTP 请求之后可能 CPU 不足并可能被终止。

如果你想要后台线程 运行, select always-on CPU.

How to allocate always-on CPU