杀死或停止活动线程

时间:2015-01-28 20:21:56

标签: python multithreading raspberry-pi gpio omxplayer

我已经走了很长一段路,我几乎就在那里。我已经从使用线程转换为线程,现在可以在播放过程中切换视频,但我仍然无法查看或停止第一个视频。基本上,我使用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

1 个答案:

答案 0 :(得分:3)

您需要实现自己的线程:

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()