
*****
### 面試題
> 描述Python GIL的概念,以及它對Python多線程的影響
1.主線程死循環
```
while True:
pass
```
2.2個線程死循環
~~~
import threading
# 子線程死循環
def test():
while True:
pass
t1 = threading.Thread(target=test)
t1.start()
# 主線程死循環
while True:
pass
~~~
3.2個進程死循環
~~~
import multiprocessing
def deapLoop():
while True:
pass
# 子進程死循環
p1 = multiprocessing.Process(target=deapLoop)
p1.start()
# 主進程死循環
while True:
pass
~~~
### 參考答案
> python語言和GIL沒有關系,僅僅是由于歷史原因在Cpython虛擬機,難以移除GIL
> GIL:全局解釋器鎖。每個線程在執行的過程都需要先獲取GIL,保證同一時刻只有一個線程可以執行代碼
> 線程釋放GIL鎖的情況:在IO操作等可能會引起阻塞的system call之前,可以暫時釋放GIL,但在執行完畢后,必須重新獲取GIL,Python3使用計時器
> Python使用多進程是可以利用多核的CPU資源的
> 多線程爬取比單線程性能有提升,因為遇到IO阻塞會自動釋放GIL鎖