Answer the question
In order to leave comments, you need to log in
For some reason, when I work with a class not through the main thread, the variables in the class do not change, why?
import time
from threading import Thread
class Human():
def __init__(self, id):
self.hp = 100
self.defence = 0
self.attack = 2
self.tycoons = {}
self.id = id
self.money=0
self.isworking = 0
def work(self):
if self.isworking == 0:
self.isworking = 1
print("Вы идете на подработку.")
time.sleep(1)
give = randint(2000, 2500)
print(f"Работа завершена, получено {give} рублей.")
self.money+=give
self.isworking = 0
elif self.isworking==1:
print(f"Вы уже работаете! (К сожалению вы не умеете разделяться на 2 части и работать на двух разных работах одновременно)")
per=Human(1)
th=Thread(target=per.work, args=())
th.start()
th=Thread(target=per.work, args=())
th.start()
Answer the question
In order to leave comments, you need to log in
Well, the second is just understandable, you run work () for the same class.
While the first copy of work() sleeps in time.sleep(1), the second one starts running, since everything happens in separate threads. The second one sees isworking = 1 and stops.
Due to the lack of any synchronization of threads working with the same object, the result is undefined.
In the presented code, 2 threads are launched in a row, without waiting for the completion of each of them. And the result was probably checked in the main thread while both threads were still running.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question