A
A
armageddon2342021-11-19 16:53:23
Python
armageddon234, 2021-11-19 16:53:23

How to drag a value from a class from a function to another class into a function?

I have been given a task. I launched two cycles at the same time and I need to transfer dej1 and dej2 to the second class in a function, I don’t know how to use it, and I probably can’t call the function a second time. How can I use dej1 and dej2 from the first class in the second class

class search_time(Thread):
  def run(self):
    run_time = True
    while run_time:
      run_search_time_1 = True
      run_search_time_2 = False
      while run_search_time_1:
        date = datetime.datetime.today()
        time_day = str(date.strftime('%H:%M:%S'))
        if time_day == "16:43:00" or time_day == "16:43:01" or time_day == "16:43:02":
          dej1 = random.randint(1, 27)
          dej2 = random.randint(1, 27)
          dej = True
          while dej:
            if dej1 == dej2:
              dej2 = random.randint(1, 27)
            if dej1 != dej2:
              dej = False			
          run_search_time_2 = True		
          run_search_time_1 = False
      while run_search_time_2:
        date = datetime.datetime.today()
        time_day = str(date.strftime('%H:%M:%S'))
        if time_day == "16:44:00":
          run_search_time_1 = True
          run_search_time_2 = False

class runbot(Thread):
  def run(self):
    for event in longpoll.listen():
      if event.type == VkBotEventType.MESSAGE_NEW:
        if event.from_chat:

          id = event.chat_id
          msg = event.object.message['text'].lower()

          if msg == 'кто дежурный':
            vk_session.method('messages.send', {'chat_id' : id, 'message' : 'Дежурные сегодня: ' + student[dej1] + ' и ' + student[dej2], 'random_id' : 0})

w1 = search_time()
w1.start()
w2 = runbot()
w2.start()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-19
@armageddon234

The easiest way is to move variables from local to an instance of the class. And then add a constructor to the second class, and pass a link to the first class. But in order to avoid race conditions (when two threads get into one variable, and at least one of them is written), you need to hide the dej1 and dej2 variables under a mutex (Lock in Python terms).

class search_time(Thread):
  def __init__(self):
    super().__init__()
    self.dej = ""
    self.dej2 = ""
    self.dej_mutex = threading.Lock()
  def run(self):
    #в коде run запись в self.dej1 или self.dej2 делается строго так
    if self.dej_mutex.acquire(): #если Lock уже занят вторым потоком, первый подождёт освобождения
      self.dej1 = "Вася Пупкин"
      self.dej2 = "Жора Золотарёв"
      self.dej_mutex.release() #а теперь сами освободим Lock, чтобы второй поток мог обратиться к переменным

In the second thread, you create a constructor, and pass it a reference to the first thread.
class runbot(Thread):
  def __init__(self, st):
    super().__init__()
    self.st = st
  def run(self):
    #в коде обращение к dej1 или dej2 делается строго так
    if self.st.dej_mutex.acquire(): #если Lock сейчас занят первым потоком, ждём освобождения
      print(self.st.dej1, self.st.dej2) #используем переменные
      self.st.dej_mutex.release() #а теперь сами освободим Lock, чтобы первый поток мог обратиться к переменным

Then when creating threads, do this:
w1 = search_time()
w1.start()
w2 = runbot(w1)
w2.start()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question