S
S
simplepy2021-12-03 20:36:31
Python
simplepy, 2021-12-03 20:36:31

Question about the ducts, how to do something after they are completed?

In general, I have a telegram bot.
When writing the /work command, it launches thread 1, which launches 100 other X threads, and I need somehow after the completion of these X threads, thread 1 issued something and the whole bot worked, and if another user writes /work, then everything worked too

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LXSTVAYNE, 2021-12-04
@lxstvayne

You probably need something similar to this:

from threading import Thread
from time import sleep


def hard_calculations():
    # some calculations...
    sleep(0.3)


class CustomThread(Thread):
    def __init__(self):
        super().__init__()
        self._result = None

    def run(self) -> None:

        threads = []
        for i in range(5):
            t = Thread(target=hard_calculations)
            t.start()
            threads.append(t)

        # Дожидаемся выполнения всех потоков
        for thread in threads:
            thread.join()

        print(f'{self.name} is done!')
        self._result = 'furfurfur'

    @property
    def result(self):
        return self._result


if __name__ == '__main__':
    t = CustomThread()
    t.start()
    t.join()  # Дожидаемся завершения нашего `главного` потока

    print(t.result)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question