如果GIL存在,Python中的多线程有什么意义? [英] What's the point of multithreading in Python if the GIL exists?

查看:342
本文介绍了如果GIL存在,Python中的多线程有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,GIL使得不可能拥有单独利用每个内核的线程.

From what I understand, the GIL makes it impossible to have threads that harness a core each individually.

这是一个基本问题,但是threading库的意义是什么?如果线程代码具有与普通程序相同的速度,这似乎毫无用处.

This is a basic question, but, what is then the point of the threading library? It seems useless if the threaded code has equivalent speed to a normal program.

推荐答案

在某些情况下,应用程序甚至可能无法充分利用一个内核,而使用线程(或进程)可能会帮助实现这一目标.

In some cases an application may not utilize even one core fully and using threads (or processes) may help to do that.

考虑一个典型的Web应用程序.它接收来自客户端的请求,对数据库进行一些查询,然后将数据返回给客户端.鉴于IO操作大多数时候都比CPU操作慢几个数量级,因此此类应用程序正在等待IO完成.首先,它等待从套接字读取请求.然后,它一直等到对数据库的请求写入打开到DB的套接字中.然后,它等待数据库的响应,然后将响应写入客户端套接字.

Think of a typical web application. It receives requests from clients, does some queries to the database and returns data back to the client. Given that IO operation is order of magnitude slower than CPU operation most of the time such application is waiting for IO to complete. First, it waits to read the request from the socket. Then it waits till the request to the database is written into the socket opened to the DB. Then it waits for response from the database and then for response to be written to the client socket.

等待IO完成可能需要90%(或更多)的时间来处理请求.当单线程应用程序在IO上等待时,它只是不使用内核,并且该内核可用于执行.因此,此类应用程序甚至可以在单个内核上留有空间供其他线程执行.

Waiting for IO to complete may take 90% (or more) of the time the request is processed. When single threaded application is waiting on IO it just not using the core and the core is available for execution. So such application has a room for other threads to execute even on a single core.

在这种情况下,当一个线程等待IO完成时,它将释放GIL,而另一个线程可以继续执行.

In this case when one thread waits for IO to complete it releases GIL and another thread can continue execution.

这篇关于如果GIL存在,Python中的多线程有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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