Python内部是如何存储GC引用变量的计数的?
PHP中文网
PHP中文网 2017-04-18 10:08:49
0
1
482
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
左手右手慢动作

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.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!