M
M
MaxiZm2022-02-19 21:59:28
Python
MaxiZm, 2022-02-19 21:59:28

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()

After the first launch, the amount of money does not change, and after the second and more, it starts writing as if I'm still working.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2022-02-20
@Vindicar

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.

D
Dmitry Shitskov, 2022-02-20
@Zarom

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 question

Ask a Question

731 491 924 answers to any question