4

如果我在 C# 线程中启动 IronPyThon 引擎,python 脚本将启动多个线程。但是,当我杀死 C# 线程时,python 脚本中的所有线程仍在运行。如何杀死 Python 脚本中的所有线程?

4

4 回答 4

5

简单的想法是将它作为一个开始Process

在你杀死它之后ProcessThread它也将被杀死。

于 2013-06-07T11:07:45.187 回答
0

您可以肯定地以相反的方式进行操作。因为我不知道python,所以我只会分享这个想法。

  • 在系统中设置一个命名事件(你在windows中,在c#中很简单,搜索Mutex
  • 与您的 python 主线程共享命名事件的名称
  • 在主 python 线程中设置一个终止标志,可由 worker-python-threads 访问
  • 设置 worker-python-threads 以偶尔监控此标志
  • 同样在主 python 线程中,开始一个无限循环,如下所示
  • 每当您希望它们死亡时,在 c# 线程中设置命名事件

伪代码:

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) 
}

我在 c#/c++ 之间做过类似的场景,到目前为止,它在所有情况下都取得了成功。我希望它适合python虽然..

于 2013-06-13T19:18:14.857 回答
0

如果您确定要杀死它们,您所做的就是遍历进程列表并检查每个进程的父 ID。如果父 ID 与您启动的 IronPython 进程的 ID 相同,则将其终止。这将杀死与该进程关联的所有线程。像这样的东西,其中 processes 是 Processes 的完整数组,而 parent 是您启动的 IronPython 进程:

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

如果您担心 IP 子进程会产生自己的进程,则需要将其转换为递归解决方案。

于 2013-06-11T18:46:41.060 回答
0
  1. If your thread loops executing something on each iteration, you can set a volatile boolean flag such that it exits after finishing the current iteration (pseudocode because I'm not familiar with python):

        while shouldExit = false
    // do stuff
    
  2. Then just set the flag to true when you want the thread to stop and it will stop the next time it checks the condition. If you cannot wait for the iteration to finish and need to stop it immediately, you could go for Thread.Abort, but make absolutely sure that there is no way you can leave open file handles, sockets, locks or anything else like this in an inconsistent state.

于 2013-06-12T16:39:32.647 回答