简体   繁体   English

离开页面时停止线程运行

[英]Stop the thread running when leaving page

Im using this guys code so I can stream video from my PiCamera 即时通讯使用这个家伙代码,所以我可以从我的PiCamera视频流

camera_pi.py: 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()

Main Flask App(This is a part of my code: Main Flask App(这是我的代码的一部分:

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: 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>

My whole project works fine till i render the stream.html page and call the streaming functions. 在我渲染stream.html页面并调用流功能之前,我的整个项目工作正常。 When you actually load another page it seems that the streaming thread still running right? 当您实际加载另一个页面时,似乎流线程仍在运行吗? Is there any way to kill the thread when I leave the stream.html page? 我离开stream.html页面时,有什么方法可以杀死线程吗? Leaving the stream.html means you are not streaming anymore, so the thread is not needed to be running. 离开stream.html意味着您不再流媒体,因此不需要运行线程。 The reason is that is killing my pi memory with no reason. 原因是无缘无故地杀死了我的pi记忆。

Killing threads is not supported. 不支持终止线程。 Just add to your thread's loop a check for a global flag, such as: 只需在线程循环中添加全局标志检查即可,例如:

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

(and after the loop do whatever's needed to properly close the camera, if anything). (在循环之后,请执行任何操作以正确关闭相机,如果有的话)。

In your main code, set global stop_the_thread to False at the start, and then to True at the time you determine the thread must stop. 在您的主代码中,首先将global stop_the_thread设置为False ,然后在确定线程必须停止时将其设置为True

It's more elegant, in this specific case, to use a class attribute cls.stop_the_thread rather than an actual global variable, but that doesn't affect the key concepts. 在这种特定情况下,使用类属性cls.stop_the_thread而不是实际的全局变量更为优雅,但这不会影响关键概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM