java—何时在jython中使用cleanup()

hjzp0vay  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(264)

有必要打电话吗 cleanup() 之前 close() 在一个 PythonInterpreter 每次都在jython?
我一直在看文档,但是我没有找到关于这个函数的很多信息。javadocs什么都没说。我找到的最接近的信息是在readthedocs中,它们解释了在某些情况下使用线程编程时需要进行清理,我甚至不确定它们是否引用了这个特定函数。
我不知道什么时候需要打电话 cleanup() ... 如果答案总是,那他们为什么要 cleanup() 以及 close() 单独的功能?

6psbrbz9

6psbrbz91#

好的,我已经阅读了jython的源代码并做了一些测试。以下是我的发现:
什么 cleanup() does:它负责未绑定的资源,比如运行线程和文件。
什么 cleanup() 不:以任何形式重置解释器的状态;导入的模块和定义的变量被保留。
以下示例显示了此行为:

例1

让我们导入一个模块,定义一个变量并打开一个文件。

PythonInterpreter py = new PythonInterpreter();

String code1 = "import sys;"
        + "a=45;"
        + "f = open('test.txt')";
String code2 = "print(sys.version_info);"
        + "print(a);"
        + "print(f.closed)";

// first execution
py.exec(code1);
py.exec(code2);

// second execution
py.cleanup();
py.exec(code2);

py.close()

it输出

sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
45
False
------
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
45
True

模块 sys 以及变量 a 以及 f 清理后仍然存在具有相同值的文件,但打开的文件已关闭。

例2

为了这个, func 是一个缓慢的功能,大约需要2秒才能完成(比正常的 cleanup() ).

PythonInterpreter py = new PythonInterpreter();

String code3 = "from threading import Thread\n"
        + "def func():\n"
        + "  print 'th start'\n"
        + "  for i in range(0,20000000):\n"
        + "    x=i\n"
        + "  print 'th done'\n"
        + "th = Thread(target=func)\n"
        + "th.start()";
String code4 = "print th.isAlive()\n"
        + "th.join()";

// first execution
py.exec(code3);
py.exec(code4);
System.out.println("------");   

// second execution
py.exec(code3);
py.cleanup();
py.exec(code4);

py.close();

输出:

th start
True
th done
------
th start
th done
False

在第一次执行中,主线程有足够的时间检查 th 是活生生的然后打印出来。在第二种情况下,它总是等待 th 结束,意味着 cleanup() 在某处连接线。

结论

正如@mzjn所指出的 close() 函数调用 cleanup() 这很有道理,所以你不需要打电话 cleanup() 之前 close() . 如果您想继续使用 PythonInterpreter 但需要关闭所有打开的文件并连接所有线程。

相关问题