离开页面时停止线程 运行

Stop the thread running when leaving page

我正在使用 this 伙计们的代码,所以我可以从我的 PiCamera 流式传输视频

camera_pi.py:

import time
import io
import threading
import picamera


class Camera(object):
    thread = None  # background thread that reads frames from camera
    frame = None  # current frame is stored here by background thread

    def __init__(self):
        if self.thread is None:
            # start background frame thread
            self.thread = threading.Thread(target=self._thread)
            self.thread.start()

            # wait until frames start to be available
            while self.frame is None:
                time.sleep(0)

    def get_frame(self):
        return self.frame

    @classmethod
    def _thread(cls):
        with picamera.PiCamera() as camera:
            # camera setup
            camera.resolution = (1280, 720)
            camera.hflip = False
            camera.vflip = False

            # let camera warm up
            camera.start_preview()
            time.sleep(2)

            stream = io.BytesIO()
            for foo in camera.capture_continuous(stream, 'jpeg',
                                                 use_video_port=True):
                # store frame
                stream.seek(0)
                cls.frame = stream.read()

                # reset stream for next frame
                stream.seek(0)
                stream.truncate()

Flask 主应用程序(这是我的代码的一部分:

from camera_pi import Camera
@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

Stream.html:

<div class="panel panel-default">
  <div class="panel-heading">
    <h1 class="panel-title">Live Streaming</h1>
  </div>
  <div class="panel-body">
    <img id="pic" src="{{ url_for('video_feed') }}" alt="live stream link" class="img-responsive img-rounded"></img>
  </div>
</div>

我的整个项目工作正常,直到我呈现 stream.html 页面并调用流式处理函数。当您实际加载另一个页面时,似乎流线程仍然 运行 对吗? 当我离开 stream.html 页面时,有什么方法可以终止线程吗?离开 stream.html 意味着您不再流式传输,因此线程不需要 运行。原因是无缘无故地杀死了我的 pi 内存。

不支持终止线程。只需在线程的循环中添加一个全局标志检查,例如:

        for foo in camera.capture_continuous(stream, 'jpeg',
                                             use_video_port=True):
            if stop_the_thread: break

(并在循环后执行任何正确关闭相机所需的操作,如果有的话)。

在您的主代码中,在开始时将全局 stop_the_thread 设置为 False,然后在您确定线程必须停止时设置为 True

在这种特定情况下,使用 class 属性 cls.stop_the_thread 而不是实际的全局变量更优雅,但这不会影响关键概念。