简体   繁体   English

在python中终止线程,进程,函数

[英]Terminate thread, process, function in python

I'm quite new at python and for a while I try to fight specific problem. 我是python的新手,有一段时间我尝试解决特定问题。 I have function to listen and print radio frames.To do that I'm using NRF24 Lib and whole function is so easy. 我具有监听和打印广播帧的功能。为此,我使用的是NRF24 Lib,整个功能非常简单。 The point is that I run this function and from time to time I need to terminate it and again run. 关键是我运行了此功能,有时我需要终止它并再次运行。 So in code it looks like 所以在代码中看起来像

def recv():
    radio.openWritingPipe(pipes[0])
    radio.openReadingPipe(1, pipes[1])
    radio.startListening()
    radio.stopListening()
    radio.printDetails()
    radio.startListening()
    while True:
        pipe = [0]
        while not radio.available(pipe):
            time.sleep(10000/1000000.0)
        recv_buffer = []
        radio.read(recv_buffer)           
        print(recv_buffer)

I run this function from a server side and now I want to stop it and run again? 我从服务器端运行此功能,现在我想停止它并再次运行? There is it posible ? 有可能吗? why I just cant recv.kill()? 为什么我不能recv.kill()? I read about threading, multiprocessing but all this didn't give me proper result. 我读到了有关线程,多处理的信息,但所有这些都没有给我适当的结果。

How I run it: 我如何运行它:

    from multiprocessing import Process
      def request_handler(api: str, arg: dict) -> dict:
          process_radio = Process(target=recv())

      if api == 'start_radio':
           process_radio.start()
           ...

      elif api == 'stop_radio':
           process_radio.terminate():
           ...
...

There is no way to stop a Python thread "from the outside." 没有办法从外部停止Python线程。 If the thread goes into a wait state (eg not running because it's waiting for radio.recv() to complete) there's nothing you can do. 如果线程进入等待状态(例如,由于正在等待radio.recv()完成而未运行),则您无能为力。

Inside a single process the threads are autonomous, and the best you can do it so set a flag for the thread to action (by terminating) when it examines it. 在单个进程内,线程是自治的,并且最好的办法是在检查线程时为线程设置一个标志以使其行动(通过终止)。

As you have already discovered, it appears, you can terminate a subprocess, but you then have the issue of how the processes communicate with each other. 正如已经发现的那样,它可以出现,您可以终止子流程,但是接下来便遇到了流程之间如何通信的问题。

Your code and the test with it don't really give enough information (there appear to be several NRF24 implementations in Python) to debug the issues you report. 您的代码及其测试实际上并没有提供足够的信息(Python中似乎有多个NRF24实现)来调试您报告的问题。

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

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