3

我编写了一个漂亮的多线程脚本,当我运行它时,它在 25 个线程中的表现比直接调用线程处理程序时更差。

然后我发现了全局解释器锁。我想问,在我为这个脚本丢弃 python 并用其他东西重写之前,有没有办法在 python 中进行实际工作的多线程?

4

5 回答 5

8

另一种方法是放弃线程,转而使用Multiprocessing模块 (Python 2.6+),它绕过 GIL,并且具有至少类似于线程模块中的 API。

于 2010-12-07T20:30:30.673 回答
3

现在这是一个有趣的问题——我认为在直接的 CPython 中没有转义 GIL。

Stackless Python应该通过使用microthreads提高了 CPython 的“并发”性能,但我认为它不会逃脱 GIL。

此外,根据python.org 上的 GIL 页面,Jython 和 IronPython 没有 GIL。

于 2010-12-07T20:25:33.957 回答
1

The correct answer depends heavily on what you're doing.

Heavily CPU-bound (and blocking IO-bound) tasks, like compression and image rendering, are usually done with native code, and native libraries normally release the GIL while they work, which allows concurrency. When you can isolate the CPU-intensive work to a narrow native call, you get concurrency, native performance where it counts, and the convenience of writing most of the code in Python.

Not all code has those small, isolatable blocks of computational code that can be neatly implemented in a native library, but a whole lot do.

于 2010-12-07T21:26:17.397 回答
0

如果它适用于您的问题,您可以尝试多处理模块。

于 2010-12-07T20:31:11.250 回答
0

据我所知,在 CPython(C 中 Python 的实现)中,不。(如果我错了,请纠正我,我很想知道是否存在解决方案!)。

您可能想对 IronPython (.NET) 或 JPython (Java/JWM) 感兴趣。我没有使用过它们,但我相信其中至少有一个支持给定执行环境的原生线程。

于 2010-12-07T20:23:09.603 回答