Home  >  Q&A  >  body text

Python内部是如何存储GC引用变量的计数的?

PHP中文网PHP中文网2741 days ago503

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:10:49

    This is easier to understand. GIL ensures that python byte code only has one native thread running in the process at the same time. However, the logic of the byte code itself still requires locking/mutual exclusion, etc. to ensure that the thread can be reentrant, because the byte code may be interrupted at any point during the running process and switched to another thread.

    A simple example:

    A piece of counter code:

    // Step 1
    counter = get_counter()
    // Step 2
    counter += 1
    // Step 3
    set_counter(counter)

    Assume that the initial Counter is 0, and two threads execute this Python code at the same time without any synchronization.

    The expected result should be that both threads have counted, and the final Counter should be 2:


    But because there is no locking/mutual exclusion, the execution situation is as follows:

      When thread A finishes executing Step 1, the counter is 0, which means switching to thread B
    1. Thread B successfully executed Steps 1, 2, and 3. Now Counter is 1, and then switches to A
    2. Thread A continues to execute Step 2 and gets counter to 1, and then Step 3 sets Counter to 1.
    3. The final result is 1.

    reply
    0
  • Cancelreply