S
S
Sazoks2021-03-24 11:00:02
Python
Sazoks, 2021-03-24 11:00:02

How to delete the thread object when it ends?

Good day!
I have a SocketServer class. In it, I run several threads for rooms:

def __init__(self, socket_io_p, start_list_events):
        """
        Инициализатор класса.
        :param socket_io_p: Серверный сокет для общения с клиентами.
        :param start_list_events: Начальный набор событий.
        """

        # Наш серверный сокет.
        self.__socket_io = socket_io_p

        # Запускаем обработчики.
        self.client_join_room = self.__socket_io.on("join")(self.__client_join_room)
        self.client_leave_room = self.__socket_io.on("leave")(self.__client_leave_room)

        # Начальный набор трансляций и список комнат.
        # По ходу работы будет изменяться в размерах из-за добавления
        # или завершения трансляций.
        self.__event_threads = []
        self.__list_rooms = []
        for i, event in enumerate(start_list_events):
            self.__list_rooms.append(event.room)
            self.__event_threads.append(Thread(target=self.__room_thread,
                                               args=(event,)))
            self.__event_threads[i].start()
            print(f"{event.room} started")


There is a list of rooms (streams) here - self.__list_rooms. But it is vital for me that when the work ends, the Thread object itself in this list is deleted.

In the self.__room_thread method, I wrote the following, but immediately tugged at my sleeve, realizing that this is complete nonsense (I guess):
with Lock():
            # По окончании трансляции удаляем комнату и поток.
            for i, room in enumerate(self.__list_rooms):
                if room == current_room:
                    self.__event_threads.pop(i)
                    self.__list_rooms.pop(i)
                    print(f"{room} deleted")
                    break


I simply access the list through the mutex and delete the necessary data. But I thought that it turns out the object will delete itself, although the work has not yet been completed.

In general, one should remove the Thread() object from the list when the thread terminates.

Thanks for answers!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-03-24
@dmtrrr

I didn't run the code

it's an interesting approach to development
you need to remove the Thread() object from the list when the thread terminates.

And what's the point in adding this object to the list?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question