销毁对象时的运行方法 [英] Running method while destroying the object

查看:63
本文介绍了销毁对象时的运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我的朋友告诉我有关情况,他们参与了他们的项目. 有人决定,最好在并行线程中(如异步地)销毁NotVerySafeClass的对象.它是在前一段时间实施的. 现在它们崩溃了,因为在主线程中调用了某些方法,而对象却被销毁了. 创建了一些解决方法来处理这种情况.

A few days ago my friend told me about the situation, they had in their project. Someone decided, that it would be good to destroy the object of NotVerySafeClass in parallel thread (like asynchronously). It was implemented some time ago. Now they get crashes, because some method is called in main thread, while object is destroyed. Some workaround was created to handle the situation.

当然,这只是一个不是很好解决方案的示例,但仍然是一个问题:

Ofcourse, this is just an example of not very good solution, but still the question:

是否有某种方法可以防止NotVerySafeClass内部出现这种情况(如果已经调用了destructor,则拒绝运行methods,并强制destructor等待,直到所有正在运行的method都结束了(假设只有一个method))?

Is there some way to prevent the situation internally in NotVerySafeClass (deny running the methods, if destructor was called already, and force the destructor to wait, until any running method is over (let's assume there is only one method))?

推荐答案

不,不,不.这是一个基本的设计问题,它在思考多线程情况和一般的竞争条件时显示出一个常见的误解.

No, no and no. This is a fundamental design issue, and it shows a common misconception in thinking about multithreaded situations and race conditions in general.

有一种事情可能同样发生,这实际上表明您需要一个所有权概念:函数调用线程可以在对象被销毁后立即调用该函数,因此不再有对象并尝试在UB上调用函数,由于该对象已不存在,因此它也没有机会防止dtor和成员函数之间的任何交互.

There is one thing that can happen equally likely, and this is really showing that you need an ownership concept: The function calling thread could call the function just right after the object has been destroyed, so there is no object anymore and try to call a function on it is UB, and since the object does not exist anymore, it also has no chance to prevent any interaction between the dtor and a member function.

这篇关于销毁对象时的运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆