Different results with thread in Python 2/3
<p>Below is the code in Python 3. It always can get 100000. Why it is wrong? I think it should have different results.</p>

<pre><code>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)
</code></pre>

<p>Below is the code in Python 2. It always has different result (random). </p>

<pre><code>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
</code></pre>

<p>CPython 2 allowed threads to switch after a certain number of byte codes had executed; CPython 3.2 changed to allow threads to switch after a certain amount of time has passed.  Your <code>test()</code> executes plenty of byte codes, but consumes little time.  On my box, under Python 3 the displayed result becomes unpredictable if I add, e.g., this near the start:</p>

<pre><code>import sys
sys.setswitchinterval(sys.getswitchinterval() / 10.0)
</code></pre>

<p>That is, allow threads to switch after 10 times less time (than the default) has elapsed.</p>

<p>Also note that <code>_thread</code> is strongly discouraged in Python 3:  that's why the leading underscore was added.  Using <code>threading.Thread</code> instead, like:</p>

<pre><code>for i in range(10):
    t = threading.Thread(target=test)
    t.start()
</code></pre>

python python-3.x python-2.x