Issue1203

classification
Title: Many threads: unpredictable results
Type: Severity: major
Components: Core Versions: Deferred
Milestone:
process
Status: closed Resolution: invalid
Dependencies: Superseder:
Assigned To: Nosy List: cgroves, gunter.bach
Priority: Keywords:

Created on 2008-12-15.13:30:13 by gunter.bach, last changed 2008-12-16.17:39:34 by cgroves.

Messages
msg3920 (view) Author: Gunter (gunter.bach) Date: 2008-12-15.13:30:12
This naive program creates 10000 threads. More than 2000 of them are not
executed completely:

-----
import thread, time

cnt_a = cnt_b = 0
def test():
    global cnt_a, cnt_b
    time.sleep(1)
    cnt_a += 1
    time.sleep(1)
    cnt_b += 1

i = 10000
while i:
    i -= 1
    thread.start_new_thread(test, ())

time.sleep(100)
print cnt_a, cnt_b
----

The program prints two different numbers not equal to 10000.

Tested on Linux, Jython2.1, java1.5.0 and Windows, Jython2.5a3, jdk1.6.0_01.
msg3927 (view) Author: Charlie Groves (cgroves) Date: 2008-12-15.18:15:39
I'd guess that the threads all execute, but because Jython doesn't have
a GIL, several of the increments to cnt_a and cnt_b are stomped on by
other threads.  To make this work properly you can lock around
incrementing the counters, or use
java.util.concurrent.atomic.AtomicInteger instead of plain Python ints.
msg3933 (view) Author: Gunter (gunter.bach) Date: 2008-12-16.10:47:59
Confirmed!
By using Locks it works fine.

Thanks for your quick answer!
History
Date User Action Args
2008-12-16 17:39:34cgrovessetstatus: open -> closed
resolution: invalid
2008-12-16 10:47:59gunter.bachsetmessages: + msg3933
2008-12-15 18:15:40cgrovessetnosy: + cgroves
messages: + msg3927
2008-12-15 13:30:13gunter.bachcreate