python gil 多核_Python GIL是否可以防止多核计算机上的CPU使用率超过100%?

Many references say that, Python GIL lower down the performance of multi threading code in multi core machine, since each thread will need to acquire the GIL before executioin.

In other words, it looks like GIL make a multi threading Python program to a single thread mode in fact.

For example:

(1) Thread A get GIL, execute some time, release GIL

(2) Thread B get GIL, execute some time, release GIL

...

However, after some simple experiments, I found that although GIL lower down the performance, the total CPU usage may exceed 100% in multiple core machine.

from threading import Thread

def test():

while 1:

pass

for i in range(4):

t = Thread(target=test)

t.start()

On a 4 core, 8 thread machine, the above program will occupy around 160% CPU usage.

Is there anything I misunderstand? Two threads can execute exactly at the same moment? Or the CPU usage calculation has bias or something wrong?

Thanks

解决方案

In all likelyhood, the extra 60% CPU usage you're seeing is simply your various threads fighting over the GIL.

There is, after all, some time spent outside the GIL where the interpreter is working to release/acquire the GIL and the O/S scheduler being at work to arbitrate them.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值