Object delete itself from container(对象从容器中删除自身)
问题描述
所以我有一个容器(任何类型,可能是 std::map 或 std::vector),它包含一个类的对象,其中一些网络事物在一个线程中运行,检查它是否仍然连接(线程在内部定义该类并在构造时启动).
So I have a container(any kind, probably std::map or std::vector) which contains objects of a class with some network thing running in a thread that checks if it is still connected (the thread is defined inside that class and launches when constructed).
有什么方法可以让对象在断开连接时从容器中删除自己,或者我应该将线程移到对象之外并使用该类来存储数据?
Is there any way I can make the object delete itself from the container when its disconnected or should I move the thread outside the object and use that class just to store data?
推荐答案
我会有卸载队列.
当一个线程注意到连接断开时,它会将对象(和 continer)注册到卸载队列中,尽可能地让一切都上升,然后线程终止.
When a thread notices that the connection is down it registers the object (and continer) with the unload queue tides everything up as much as possible then the thred terminates.
然后一个单独的线程位于卸载队列中.它的唯一目的是监视队列.当它在队列中看到一个新对象时,将其从容器中移除,然后将其销毁(根据需要与对象线程同步).
A separate thread is then inside the unload queue. Its sole purpose is to monitor the queue. When it sees a new object on the queue, remove it from the container and then destroy it (syncing with the objects thread as required).
这篇关于对象从容器中删除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象从容器中删除自身
基础教程推荐
- 使用scanf()读取字符串 1970-01-01
- C++ #define 1970-01-01
- C语言访问数组元素 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- C++按值调用 1970-01-01
- C++定义类对象 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- 初始化变量和赋值运算符 1970-01-01