繁体   English   中英

杀死或停止活动线程

[英]Killing or stopping an active thread

我走了很长一段路,我快到了。 我已经从使用“线程”转换为“线程”,现在可以在播放中切换视频,但是我仍然无法杀死或停止第一个视频。 基本上,我正在使用OMXplayer制作由Raspberry Pi上的按钮控制的视频播放器。 目前,我必须先等待一个视频播放完毕,然后再按下另一个按钮,否则它将崩溃,因为同时播放多个视频。

非常感谢你们提供的任何帮助。

#!/usr/bin/python

import RPi.GPIO as GPIO
import subprocess
import threading
import time

GPIO.setmode (GPIO.BCM)
GPIO.setwarnings (False)

GPIO.setup(9, GPIO.IN)  # Button 1
GPIO.setup(10, GPIO.IN) # Button 2

def shoppingcart():
        global current_video
        while True:
                if GPIO.input(9):
                        #current_video.terminate()
                        #current_video.kill()
                        print "Play Shoppingcart"
                        time.sleep(1)
                        current_video=subprocess.Popen(['omxplayer','-b','Desktop/videos/shoppingcart.mp4'],
                                        stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,close_fds=True)

def dodgeballs():
        global current_video
        while True:
                if GPIO.input(10):
                        #current_video.terminate()
                        #current_video.kill()
                        print "Play Dodgeballs"
                        time.sleep(1)
                        current_video=subprocess.Popen(['omxplayer','-b','Desktop/videos/dodgeballs.mp4'],
                                        stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,close_fds=True)

v1 = threading.Thread( name='shoppingcart', target=shoppingcart ) # Videos thread
v2 = threading.Thread( name='dodgeballs', target=dodgeballs )   # Videos thread

v1.start()
v2.start()

while True:
        pass

GPIO.cleanup() #Reset GPIOs

您需要实现自己的线程:

class RaspberryThread(threading.Thread):
    def __init__(self, function):
        self.running = False
        self.function = function
        super(RaspberryThread, self).__init__()

    def start(self):
        self.running = True
        super(RaspberryThread, self).start()

    def run(self):
        while self.running:
            self.function()

    def stop(self):
        self.running = False

然后从函数中删除while循环,以便可以将其传递给线程。

v1 = RaspberryThread(function = shoppingcart)
v2 = RaspberryThread(function = dodgeballs)

v1.start()
v2.start()

然后您可以随时停止线程

v1.stop()
v2.stop()

暂无
暂无

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

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