码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-08-19 00:19:51      阅读:553      评论:0      收藏:0      [点我收藏+]

标签:

看到论坛上有人问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吧。。。。。。

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

标签:

原文地址:http://www.cnblogs.com/kzcdqbz/p/4741017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!