c++ - 线程调用的函数是否对对象删除安全?

标签 c++ multithreading thread-safety

我想知道线程 1 是否通过传递的对象“obj->fun()”调用类函数,并且该对象在后台被其他线程删除,比如线程 2 线程 1 执行的函数会发生什么情况。

例子:

ClassA {
  int functionA() {
    ...condition(started_execution);
    int a=0;
    a++;
    printf(....a);
    return a;
  }
};
void startExecution(void *arg) {
/*casting code object A*/
  A->functionA();
}

int main() {
  ClassA *A = new ClassA();
  pthread_create(....,startExecution,(void *)A);
  ....wait_for(started_execution);
    delete A;//just want to know the behaviour and not join method.
}

问题:在上面的场景中,A->functionA调用了函数functionA。如果函数正在执行,删除 A 对函数执行有什么影响,因为对象 A 调用了它? functionA 不处理共享数据?

最佳答案

If the function is executing, what will the impact of delete A on function execution since object A invoked it?

如果执行函数以任何方式使用 this,其影响将是未定义的行为。通过使用 this 我的意思是访问任何数据成员或基础子对象,调用任何成员函数,间接 this 或将 this 传递给某个函数做任何这些事情。

你的 functionA 在设置条件变量后似乎没有以任何方式使用 this,所以不会有任何影响 - 假设条件变量访问本身是正确同步。

但是,这样做并不是一个好主意,因为在 functionA 的定义中看不到必须访问任何成员。以后更改功能时,程序员很容易不遵循该要求。

据我所知,这种情况类似于 delete this; 被认为符合标准,但有潜在危险的情况:Is delete this allowed?

关于c++ - 线程调用的函数是否对对象删除安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624280/

相关文章:

c++ - 库达 CMake : undefined reference

c++ - 使用 boost::singleton_pool 时处理 std::string/std::vector 成员变量

python - Python字典中的线程安全

c# - 与缓存交互时的线程安全

c++ - 我的链表方法有什么改进吗?

c++ - 不能在字符串中嵌入非 ASCII

java - 为什么同步在此代码中无法正常工作?

java - 如何计算我的多线程程序的运行时间

c++ - 线程构造的性能成本 : missed optimisations and memory allocation

c++ - 在线程中更改 GUI