簡體   English   中英

如何終止 Python 中的線程?

[英]How to terminate a thread in Python?

我知道這個話題已經討論過幾次,但是我已經嘗試過,或者至少嘗試了幾乎所有的解決方案,但是作為一個相當新的 python basher,我無法讓以前的任何解決方案起作用。

該腳本的基本前提是它訂閱了一個 MQTT 代理並等待命令,單個動作命令 100% 工作,但是其中一個命令需要一個循環無限期地運行,直到收到另一個命令,因此最合適的解決方案是在一個單獨的線程中運行“循環”,而主訂閱者循環繼續“監聽”下一個命令。

一切都在工作 95%,“靜態”命令通過並且任務運行良好,然后當“mtg”命令通過它時,線程和循環運行 100%,但是這是它失敗的地方,當收到下一個命令我可以確認“if”語句在將消息打印到控制台時處理命令,但是 thread.stop() 沒有運行,或者它可能運行但它不會終止線程 ---我正在拔頭發試圖弄清楚。

一些代碼:

from sys import exit
import blinkt
import threading
import time

MQTT_SERVER = '192.168.x.x'
MQTT_PORT = 1883
MQTT_TOPIC = 'mytopic'

REDS = [0, 0, 0, 0, 0, 16, 64, 255, 64, 16, 0, 0, 0, 0, 0, 0]

start_time = time.time()

class task(threading.Thread):

     def __init__(self):
         threading.Thread.__init__(self)
         self.kill = threading.Event()
         self.event = threading.Event()
         self._stop = threading.Event()

     def run(self):
#        while not self.kill.is_set(): 
         while True:
             if self.stopped():
                return
             self.start_run()

     def stop(self):
#        self.event.set()
         self._stop.set()

     def stopped(self):
         return self._stop.isSet()

     def start_run(self):
#         while True: <-- no longer needed as the run method loops the process. 
             delta = (time.time() - start_time) * 16
             offset = int(abs((delta % len(REDS)) - blinkt.NUM_PIXELS))

             for i in range(blinkt.NUM_PIXELS):
                 blinkt.set_pixel(i, REDS[offset + i], 0, 0)

             blinkt.show()
             time.sleep(0.1)

def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))
    client.subscribe(MQTT_TOPIC)

def on_message(client, userdata, msg):

    data = msg.payload
    if type(data) is bytes:
        data = data.decode('utf-8')
    data = data.split(',')
    command = data.pop(0)

    if command == 'clr' and len(data) == 0:
        blinkt.clear()
        blinkt.show()
        t1.stop()      #<--- I've tried a few ways to get the task to stop when the "clr" command is recieved
        task.stop()
        return

    if command == 'rgb' and len(data) == 4: #<-- This code block works fine, msg arrives and LEDs are set correctly
        try:
            pixel = data.pop(0)

            if pixel == '*':
                pixel = None
            else:
                pixel = int(pixel)
                if pixel > 7:
                    print('Pixel out of range: ' + str(pixel))
                    return

            r, g, b = [int(x) & 0xff for x in data]

            print(command, pixel, r, g, b)

        except ValueError:
            print('Malformed command: ' + str(msg.payload))
            return
        if pixel is None:
            for x in range(blinkt.NUM_PIXELS):
                blinkt.set_pixel(x, r, g, b)
        else:
            blinkt.set_pixel(pixel, r, g, b)
        blinkt.show()
        return


    if command == 'mtg' and len(data) == 0:
        print(command)
        t1 = task()
        t1.start()   #<-- Here is where the Thread is called to start and seems to run ok
        return

blinkt.set_clear_on_exit()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, MQTT_PORT, 60)
client.loop_forever()

您的t1變量是本地變量,因此當您退出on_message function 時它會丟失。 此外,您將 class task和實例t1task.stop()不起作用)混為一談。

為了快速修復,將t1 = None聲明為全局,然后將global t1添加到您的on_message function...

但是,我會考慮重構一些東西,以便有一個始終運行的線程來命令 Blinkt。 並且 MQTT 消息處理程序只需相應地設置其 state - 顯然是這樣的,干編碼。 所以可能會有一些愚蠢。

from sys import exit
import blinkt
import threading
import time

MQTT_SERVER = "192.168.x.x"
MQTT_PORT = 1883
MQTT_TOPIC = "mytopic"

REDS = [0, 0, 0, 0, 0, 16, 64, 255, 64, 16, 0, 0, 0, 0, 0, 0]

start_time = time.time()


class BlinktManager(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.stop_event = threading.Event()
        self.mode = None

    def run(self):
        while not self.stop_event.isSet():
            self.tick()
            self.stop_event.wait(0.1)  # instead of sleep

    def tick(self):
        if self.mode == "reds":
            self._tick_reds()

    def _tick_reds(self):
        delta = (time.time() - start_time) * 16
        offset = int(
            abs((delta % len(REDS)) - blinkt.NUM_PIXELS)
        )

        for i in range(blinkt.NUM_PIXELS):
            blinkt.set_pixel(i, REDS[offset + i], 0, 0)

        blinkt.show()

    def clear(self):
        self.mode = None
        blinkt.clear()
        blinkt.show()

    def set_all_pixels(self, r, g, b):
        self.mode = None
        for x in range(blinkt.NUM_PIXELS):
            blinkt.set_pixel(x, r, g, b)
        blinkt.show()

    def set_pixel(self, x, r, g, b):
        self.mode = None
        blinkt.set_pixel(x, r, g, b)
        blinkt.show()

    def begin_reds(self):
        self.mode = "reds"


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(MQTT_TOPIC)


def on_message(client, userdata, msg):
    data = msg.payload
    if type(data) is bytes:
        data = data.decode("utf-8")
    data = data.split(",")
    command = data.pop(0)

    if command == "clr" and len(data) == 0:
        blinkt_manager.clear()

    if command == "rgb" and len(data) == 4:
        x = data[0]
        r, g, b = [int(x) & 0xFF for x in data[1:]]
        if x == "*":
            blinkt_manager.set_all_pixels(r, g, b)
        else:
            # TODO: error handling
            blinkt_manager.set_pixel(int(x), r, g, b)

    if command == "mtg" and len(data) == 0:
        blinkt_manager.begin_reds()


blinkt.set_clear_on_exit()

blinkt_manager = BlinktManager()
blinkt_manager.start()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, MQTT_PORT, 60)
client.loop_forever()

Python 程序在 python 線程中引發異常

import threading 
import ctypes 
import time 

class thread_with_exception(threading.Thread):

    def __init__(self, name): 
    threading.Thread.__init__(self) 
    self.name = name 

def run(self): 

    # target function of the thread class 
    try: 
        while True: 
            print('running ' + self.name) 
    finally: 
        print('ended') 

def get_id(self): 

    # returns id of the respective thread 
    if hasattr(self, '_thread_id'): 
        return self._thread_id 
    for id, thread in threading._active.items(): 
        if thread is self: 
            return id

def raise_exception(self): 
    thread_id = self.get_id() 
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 
          ctypes.py_object(SystemExit)) 
    if res > 1: 
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 
        print('Exception raise failure') 

t1 = thread_with_exception('Thread 1') 
t1.start() 
time.sleep(2) 
t1.raise_exception() 
t1.join() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM