What is the global interpreter lock (GIL) in CPython?

前端 未结 8 1871
悲哀的现实
悲哀的现实 2020-11-21 08:53

What is a global interpreter lock and why is it an issue?

A lot of noise has been made around removing the GIL from Python, and I\'d like to understand why that is s

8条回答
  •  有刺的猬
    2020-11-21 09:41

    I want to share an example from the book multithreading for Visual Effects. So here is a classic dead lock situation

    static void MyCallback(const Context &context){
    Auto lock(GetMyMutexFromContext(context));
    ...
    EvalMyPythonString(str); //A function that takes the GIL
    ...    
    }
    

    Now consider the events in the sequence resulting a dead-lock.

    ╔═══╦════════════════════════════════════════╦══════════════════════════════════════╗
    ║   ║ Main Thread                            ║ Other Thread                         ║
    ╠═══╬════════════════════════════════════════╬══════════════════════════════════════╣
    ║ 1 ║ Python Command acquires GIL            ║ Work started                         ║
    ║ 2 ║ Computation requested                  ║ MyCallback runs and acquires MyMutex ║
    ║ 3 ║                                        ║ MyCallback now waits for GIL         ║
    ║ 4 ║ MyCallback runs and waits for MyMutex  ║ waiting for GIL                      ║
    ╚═══╩════════════════════════════════════════╩══════════════════════════════════════╝
    

提交回复
热议问题