gpt4 book ai didi

c++ - 在运行时删除未就绪的对象 cpp

转载 作者:行者123 更新时间:2023-11-28 07:06:06 25 4
gpt4 key购买 nike

考虑下课

class test{
private: long long id;
//some field....
public: test(){};
void do_something(){
//some huge operations....
}
void do_something_else(void* arg){
//yet another huge work load.....
}
}
///////////////////////////
void* _thread(void* _ins){
test* ins=(test*)_ins;
//some work
if(<<some condition>>){delete ins;}//not thread safe, std::auto_ptr doesn't help anymore
}
///////////////////////////
int main(){
test *ins=new test();
//pass the ins to 10 thread.
}

考虑有 10 个线程使用一个共享对象,当其中一个线程删除该对象时,程序退出。问题:当对象被删除时,如何在运行时得到任何错误/异常? try-catch 没有帮助。有什么解决办法吗?!
是否有任何线程安全和一致性的方法来计算使用此对象的当前线程?
当对象准备好清除时,是否有任何基于事件的解决方案来触发事件?

提前致谢。

最佳答案

C++11 的 shared_ptrs使用引用计数值的原子递增/递减

标准保证只有一个线程会调用共享对象上的删除运算符

您需要确保您的关键部分是同步的,即:如果线程仍在使用共享对象,则不会释放它。您可以使用 std::mutex为此(可以使用互斥量和条件变量实现信号量,例如 https://stackoverflow.com/a/4793662/1938163 )

关于c++ - 在运行时删除未就绪的对象 cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com