简体   繁体   中英

Stop the thread running when leaving page

Im using this guys code so I can stream video from my 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()

Main Flask App(This is a part of my code:

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>

My whole project works fine till i render the stream.html page and call the streaming functions. 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? Leaving the stream.html means you are not streaming anymore, so the thread is not needed to be running. The reason is that is killing my pi memory with no reason.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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