python线程和c++线程的区别_python 多线程和C++多线程的区别

标签:

看到论坛上有人问python多线程和C++多线程的区别?

暖神是这样回答的:

Python有Global Interpreter Lock,所以嘛……你懂的。

C++11开始才有多线程,使用共享内存方式的线程间通信,有低级的atomic operation和memory order,以及高级的lock, condition的,却没有提供消息队列。

然后,就去找GIL(Global Interpreter Lock)的定义,下面有一个定义,wiki的定义是这样的。在stackoverflow上看到了另外一个更通俗的解释:

Suppose you have multiple threads which don‘t really touch each other‘s data. Those should execute as independently as possible. If you have a "global lock" which you need to acquire in order to (say) call a function, that can end up as a bottleneck. You can wind up not getting much benefit from having multiple threads in the first place.

To put it into a real world analogy: imagine 100 developers working at a company with only a single coffee mug. Most of the developers would spend their time waiting for coffee instead of coding.

None of this is Python-specific - I don‘t know the details of what Python needed a GIL for in the first place. However, hopefully it‘s given you a better idea of the general concept.

大概明白了一个基本的意思:GIL(全局解释器锁)会序列化线程访问,所以在加了GIL锁的情况下,多线程的优势和特点并不能真正发挥出来。甚至没有单线程跑得快,因为在acquire和relea锁的时候会执行额外的线程调度指令。这个GIL只在CPython中有,方便加载C的extension,Jython和ironpython里面是木有的。所以,在python里面应该用颗粒度更小的锁?

说到C++,上文暖神说到atomic operation,就是原子锁啦,具体的在这里有一个清晰的说明,atomic是一个好东西。。。。至于memory order,表示没看懂。。。还是老老实实的取用mutex吧。。。。。。

标签:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值