Python GIL和多线程 [英] Python GIL and multithreading

查看:80
本文介绍了Python GIL和多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的单线程应用程序与工作线程数分开.只是一个问题-该动作的执行情况如何?如果GIL阻止python同时执行多个线程,

I would like to separate my sigle-thread application to number of working threads. Just 1 question - what about performance of this action? If GIL prevents python from executing more than 1 thread at the time will I have any profit?

(从c/c ++的角度来看)另一点-无论如何,我知道每个线程只能以独占方式执行,因此在比python解释器低的级别上,我有相同的限制.

Another point (from c/c++ point of view) - as I know each thread, anyway, can be only executed exclusively, so in the lower level than python interpreter I have the same limitation.

总结:在任务切换过程中,python线程的效率是否会低于"native"线程?

Summary: Will the the python threads have lesser efficiency that 'native' thread in part of task switching?

推荐答案

不用担心GIL.根据您程序执行的操作种类(计算与I/O),您将具有不同的性能特征.如果您的程序受I/O约束,那么您可能根本不会注意到GIL.

Don't worry about the GIL. Depending on the kinds of things your program does (calculation vs. I/O) you will have different performance characteristics. If your program is I/O bound then you probably won't notice the GIL at all.

另一种方法是使用 multiprocessing 模块,其中每个进程都使用自己的Python在其自己的OS进程中运行运行.通过这种方法,您可以充分利用多个内核,并且通常更安全,因为您不必担心同步访问共享内存.

Another approach is to use the multiprocessing module where each process runs in its own OS process with its own Python runtime. You can take full advantage of multiple cores with this approach, and it's usually safer because you don't have to worry about synchronising access to shared memory.

这篇关于Python GIL和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆