python单核运行,Python线程都在单个核上执行

全局解释器锁(GIL)是Python解释器层面的一个锁,它使得在同一时刻只有一个线程能执行Python字节码。尽管CPython使用操作系统线程,但实际上在解释器内部,GIL强制执行串行执行,这意味着多线程Python应用在内存中确实有多个线程,但在执行时仍然是单线程的。GIL的存在主要是为了保护解释器内存,防止多个线程同时访问Python对象,但这也意味着程序员需要处理线程同步问题。
摘要由CSDN通过智能技术生成

The GIL is an interpreter-level lock.

This lock prevents execution of

multiple threads at once in the Python

interpreter. Each thread that wants to

run must wait for the GIL to be

released by the other thread, which

means your multi-threaded Python

application is essentially single

threaded, right? Yes. Not exactly.

Sort of.

CPython uses what’s called “operating

system” threads under the covers,

which is to say each time a request to

make a new thread is made, the

interpreter actually calls into the

operating system’s libraries and

kernel to generate a new thread. This

is the same as Java, for example. So

in memory you really do have multiple

threads and normally the operating

system controls which thread is

scheduled to run. On a multiple

processor machine, this means you

could have many threads spread across

multiple processors, all happily

chugging away doing work.

However, while CPython does use

operating system threads (in theory

allowing multiple threads to execute

within the interpreter

simultaneously), the interpreter also

forces the GIL to be acquired by a

thread before it can access the

interpreter and stack and can modify

Python objects in memory all

willy-nilly. The latter point is why

the GIL exists: The GIL prevents

simultaneous access to Python objects

by multiple threads. But this does not

save you (as illustrated by the Bank

example) from being a lock-sensitive

creature; you don’t get a free ride.

The GIL is there to protect the

interpreters memory, not your sanity.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值