Stop all threads running in IronPython

If I run IronPyThon Engine in a C # thread, a python script will launch multiple threads. However, when I kill a C # thread, all threads in the python script still work. How can I kill all threads in a Python script?

+4
source share
4 answers

A simple idea is to run it as a Process ,

after you kill Process , each Thread it will also be killed.

+5
source

If you are sure that you want to kill them, then you execute the list of processes and check each parent identifier of the process. If the parent id matches the IronPython process id that you started, you will kill it. This will kill all threads associated with this process. Something like this, where processes are the full array of processes, and the parent is the IronPython process that you started:

 private static void killProcessAndChildProcesses(Process[] processes, Process parent) { foreach (Process p in processes) { if (p.GetParentProcessId() == parent.Id) { p.Kill(); } } parent.Kill() } 

If you are concerned that child IP processes process their own spawning processes, you need to convert them to a recursive solution.

0
source
  • If your thread does something at each iteration, you can set the volatile boolean flag so that it exits after the current iteration is completed (pseudo code, because I'm not familiar with python):

      while shouldExit = false // do stuff 
  • Then just set the flag to true when you want to stop the thread, and it will stop the next time you check the status. If you cannot wait for the iteration to complete and stop it immediately, you can go to Thread.Abort, but make sure you cannot leave open file descriptors, sockets, locks, or something like that in an inconsistent state.

0
source

You can definitely do it the other way around. Since I don't know python, I will only share the idea.

  • Set a named event in the system (you are in windows, it is really simple in C #, find Mutex )
  • share name of named event with python main thread
  • The python main thread sets the completion flag, accessible by worker-python-threads
  • Set worker python threads to monitor this flag sometimes
  • In the main python thread, we also start an endless loop, as shown below
  • Set a named event in a C # stream when you want them to die

Pseudocode:

 while (Not(isNamedEventSet) && otherThreadsStillBusy) { // Do some magic to check the status of the event isNamedEventSet = ... // rest for a while, // there is nothing better than a nap while other threads do all the hard work Sleep(100) } 

I made similar scripts between C # / C ++, and it has been successful in all cases so far. I hope it is suitable for python though ..

0
source

Source: https://habr.com/ru/post/1484556/


All Articles