赵同学 2022-11-25 17:48
浏览 4
已结题

C++环境下,pthread_cancel终止一个线程时,被终止线程内部的栈变量会自动销毁吗?

下面这段代码中,主线程创建了2个子线程,线程1和线程2,在线程2中使用pthread_cancel去终止线程1,线程1终止时其内部的栈变量(如my_class)会自动销毁吗?

实测结果:LINUX环境下会自动销毁,QNX环境下不会自动销毁(根本不会调用MyClass和MyClass2的析构函数),这是为什么?LINUX和QNX的pthread都说是遵循POSIX API规范,难道是和系统实现有关系?

#include <iostream>
#include <pthread.h>
#include <thread>
using namespace std;
pthread_t thread_id_1;
pthread_t thread_id_2;
class MyClass2
{
public:
    MyClass2() {
        cout << "Build MyClass2" << endl;
    }
    ~MyClass2() {
        cout << "Destory MyClass2" << endl;
    }
};
class MyClass
{
public:
    MyClass() {
        cout << "Build MyClass" << endl;
        p = new char[1024 * 1024 *100];
    }
    ~MyClass() {
        cout << "Destory MyClass" << endl;
        free(p);
    }
    char *p;
};
void func(int i)
{
    MyClass2 c2;
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    cout << "thread 1 func:" << i << endl;
}
static void *otx_thread_1(void *arg)
{
    MyClass my_class;
    int type_value = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    cout << "thread_1 set cancle type+++++:" << type_value << endl;
    for (int i = 0; i < 10; i++) {
        func(i);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return nullptr;
}
static void *otx_thread_2(void *arg)
{
    for (int i = 0; i < 10; i++) {
        cout << "thread_2:" << i << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    int ret = pthread_cancel(thread_id_1);
    cout << "otx_thread_2 cancel thread 1 ret:" << ret << endl;
    return nullptr;
}
int main(int argc, char *argv[])
{
    cout << "Main start" << endl;

    pthread_attr_t attr;
    pthread_attr_init( &attr );
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    cout << "Main set detch" << endl;
    if (pthread_create(&thread_id_1, &attr, otx_thread_1, nullptr) != 0) {
        cout << "pthread_create() 1 error" << endl;
        return -1;
    }
    if (pthread_create(&thread_id_2, nullptr, otx_thread_2, nullptr) != 0) {
        cout << "pthread_create() 2 error" << endl;
        return -1;
    }
    if (pthread_join(thread_id_2, NULL) != 0) {
        cout << "pthread_join() 1 error";
        return -1;
    }
    while (1) {
        cout << "Main Loop" << endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return 0;
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月3日
    • 创建了问题 11月25日

    悬赏问题

    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据