简体   繁体   English

与Python 2/3中的线程不同的结果

[英]Different results with thread in Python 2/3

Below is the code in Python 3. It always can get 100000. Why it is wrong? 下面是Python 3中的代码。它总是可以得到100000.为什么它错了? 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)

Below is the code in Python 2. It always has different result (random). 下面是Python 2中的代码。它总是有不同的结果(随机)。

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

CPython 2 allowed threads to switch after a certain number of byte codes had executed; CPython 2允许线程在执行了一定数量的字节代码后切换; CPython 3.2 changed to allow threads to switch after a certain amount of time has passed. CPython 3.2更改为允许线程在经过一定时间后切换。 Your test() executes plenty of byte codes, but consumes little time. 您的test()执行大量字节代码,但消耗的时间很少。 On my box, under Python 3 the displayed result becomes unpredictable if I add, eg, this near the start: 在我的框中,在Python 3下,如果我添加,例如,这在开头附近,显示的结果将变得不可预测:

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

That is, allow threads to switch after 10 times less time (than the default) has elapsed. 也就是说,允许线程在经过10次(比默认值)时间后切换。

Also note that _thread is strongly discouraged in Python 3: that's why the leading underscore was added. 另请注意,在Python 3中强烈建议不要使用_thread :这就是添加前导下划线的原因。 Using threading.Thread instead, like: 使用threading.Thread ,如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM