理解Global interpreter lock

 

Global interpreter lock (GIL) is a mechanism used in computer language interpreters to synchronize the execution of 

threads so that only one native thread can execute at a time. An interpreter that uses GIL always allows exactly one

thread to execute at a time, even if run on a multi-core processor. 

Benefits and drawbacks

increased speed of single-threaded programs (no necessity to acquire or release locks on all data structures separately)

2. easy integration of C libraries that usually are not thread-safe

3. ease of implementation (having a single GIL is much simpler to implement than a lock-free interpreter or one using fine-grained locks).

 

 

Use of a global interpreter lock in a language effectively limits the amount of parallelism reachable through concurrency of a

single interpreter process with multiple threads. If the process is almost purely made up of interpreted code and does not

make calls outside of the interpreter for long periods of time (which can release the lock on the GIL on that thread while it

processes), there is likely to be very little increase in speed when running the process on a multiprocessor machine. Due to

signaling with a CPU-bound thread, it can cause a significant slowdown, even on single processors.

 

 

为什么要在tornado前面放nginx

原因在于,Tornado采用的的单进程单线程异步IO的网络模型。Python虽然有多线程,但是Python的解释器有GIL这点非常影响了Python

利用多核的能力,所以只能通过多进程来利用多核。既然多进程,一般就需要在前端放置nginx做为负载均衡的反向代理,或是使用这些应

用服务器的wsgi模块来管理进程的生命周期 。

对于含有IO阻塞的环境,比如网络通讯、磁盘读写, 当发生阻塞时,CPU是闲置的,此时如果就一个线程就没法处理其他事情了。

所以多线程可以提高CPU利用率。

 

 
 

 参考:线程安全及Python中的GIL

 

 

 

 
 

 

posted @ 2015-12-10 10:53  等风来。。  Views(633)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------