Various stream results in Python 2/3

The code below is in Python 3. It can always get 100,000. Why is this wrong? I think it should have different results.

import time, _thread

global count
count = 0
def test():
    global count

    for i in range(0, 10000):
        count += 1

for i in range(0, 10):
    _thread.start_new_thread(test, ())
time.sleep(5)
print(count)

The code below is in Python 2. It always has a different result (random).

import time, thread

global count
count = 0
def test():
    global count

    for i in range(0, 10000):
        count += 1

for i in range(0, 10):
    thread.start_new_thread(test, ())
time.sleep(5)
print count
+4
source share
1 answer

CPython 2 allowed threads to switch after executing a certain number of byte codes; CPython 3.2 is modified to allow threads to switch after a while. Your test()executes a lot of byte codes, but consumes little time. In my field under Python 3, the displayed result becomes unpredictable if I add, for example, this is near the beginning:

import sys
sys.setswitchinterval(sys.getswitchinterval() / 10.0)

, 10 ( ).

, _thread Python 3: . threading.Thread, :

for i in range(10):
    t = threading.Thread(target=test)
    t.start()
+5

Source: https://habr.com/ru/post/1653813/


All Articles