Найти - Пользователи
Полная версия: Питон и потоки где ошибка?
Начало » Python для новичков » Питон и потоки где ошибка?
1
y4b53
Вот код:

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.
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.
Почему 19 выводиться 2 раза? И в файл 19.txt записалось 4 раза 19.
alexx11
Потому что они не ждут когда у тебя x поменяется, не хочешь заморачиваться с синхронизацией, передавай явно аргумент в конструкторе.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB