在Python中使用多线程还是串行处理?

2024-04-27 03:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

在“视觉效果的多线程”一书中,我读到了以下几行:

Anything running in Python is the only thing running in Python, This means that if your execution callbacks are all implemented in Python, you lose much of the efficiency gains of a multithreaded system.

The Python interpreter is not threadsafe -- it cannot be run rom multiple threads simultaneously. A thread that needs to use Python must wait for its turn to use the interpreter.

为什么这句话是真的?你知道吗

这是绑定到代码的,代码是从C++内部执行的。你知道吗

static void MyCallback(const Context &context){
Auto<Lock> lock(GetMyMutexFromContext(context));
...
EvalMyPythonString(str); //A function that takes the GIL
...    
}

那么到底是什么意思呢?我们不能启用多个口译员吗?你知道吗


Tags: oftheto代码inonlythatis
1条回答
网友
1楼 · 发布于 2024-04-27 03:23:50

Anything running in Python is the only thing running in Python, This means that if your execution callbacks are all implemented in Python, you lose much of the efficiency gains of a multithreaded system.

The Python interpreter is not threadsafe it cannot be run rom multiple threads simultaneously. A thread that needs to use Python must wait for its turn to use the interpreter.

这句话是真的吗?这取决于您使用的是哪个python解释器。你知道吗

使用Cpython:由于全局解释器锁(Global Interpreter Lock,GIL),一次只能运行一个线程。因此,不能利用使用多线程的性能优势。甚至,当在Cpython中使用多个线程时,您的程序也会变慢。你知道吗

如果您想在Cpython中编写并行程序,应该使用multiprocessing。其接口与threading模块相同。你知道吗

或者,可以在Jython、Ironthon中使用多线程。你知道吗

相关问题 更多 >