简体   繁体   中英

Terminate thread, process, function in python

I'm quite new at python and for a while I try to fight specific problem. I have function to listen and print radio frames.To do that I'm using NRF24 Lib and whole function is so easy. 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()? 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." 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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