Форум сайта python.su
Вот код:
import threading
class MyThread(threading.Thread):
def run ( self ):
global x
print 'This is thread ' + str(x) + ' speaking.'
f = open("out/" + str(x) + ".txt", "a")
f.write(str(x) + "\n")
f.close()
for x in xrange ( 20 ):
MyThread().start()
This is thread 1 speaking.Почему 19 выводиться 2 раза? И в файл 19.txt записалось 4 раза 19.
This is thread 2 speaking.
This is thread 3 speaking.
This is thread 4 speaking.
This is thread 5 speaking.
This is thread 6 speaking.
This is thread 7 speaking.
This is thread 8 speaking.
This is thread 9 speaking.
This is thread 10 speaking.
This is thread 11 speaking.
This is thread 12 speaking.
This is thread 13 speaking.
This is thread 14 speaking.
This is thread 15 speaking.
This is thread 16 speaking.
This is thread 17 speaking.
This is thread 18 speaking.
This is thread 19 speaking.
This is thread 19 speaking.
Отредактировано (Ноя. 30, 2010 21:16:59)
Офлайн
Потому что они не ждут когда у тебя x поменяется, не хочешь заморачиваться с синхронизацией, передавай явно аргумент в конструкторе.
Отредактировано (Ноя. 30, 2010 21:52:19)
Офлайн