[英]Stop the thread running when leaving page
即时通讯使用这个家伙代码,所以我可以从我的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(这是我的代码的一部分:
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
(在循环之后,请执行任何操作以正确关闭相机,如果有的话)。
在您的主代码中,首先将global stop_the_thread
设置为False
,然后在确定线程必须停止时将其设置为True
。
在这种特定情况下,使用类属性cls.stop_the_thread
而不是实际的全局变量更为优雅,但这不会影响关键概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.