Skip to content
Advertisement

How to kill C pthreads created by python ctypes.LoadLibrary

The module I’m using loads C library via ctypes.LoadLibrary in __init__ and calls a function which creates two processes using pthread_create C api. Thread IDs are not stored anywhere. These processes contain while(1) loops that read and write to serial port. I want to be able to kill the library threads, use said serial port for other purposes and then restore the module functionality with importlib.reload. Right now serial port remains inaccessible until I kill python top-most script with ctrl+c.

Advertisement

Answer

You cannot kill a thread without its cooperation. It absolutely will not work. You have two choices:

  1. Change the code of the library or module so that it supports clean shutdown and the threads terminate themselves. This will require changing the while(1) loops so they have some way to exit.

  2. Isolate the library or module into its own process. You can safely reach in from the outside to terminate a process or write code to terminate the process from the inside without changing the library or module.

Fixing code that doesn’t support clean shutdown so that it does support clean shutdown is the better option if it’s practical. But sometimes it can be very difficult to add support for clean shutdown to complex code that doesn’t have it. In an ideal world, every programmer would design support for clean shutdown into every library or module.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement