When I kill a pThread in C++, do destructors of objects on stacks get called?

后端 未结 4 1037
悲&欢浪女
悲&欢浪女 2021-01-02 01:54

I\'m writing a multi-threaded C++ program. I plan on killing threads. However, I am also using a ref-counted GC. I\'m wondering if stack allocated objects get destructed whe

4条回答
  •  粉色の甜心
    2021-01-02 02:27

    
    #include
    #include
    
    class obj
    {
     public:
     obj(){printf("constructor called\n");}
     ~obj(){printf("destructor called\n");}
    };
    
    void *runner(void *param)
    {
        printf("In the thread\n");
        obj ob;
        puts("sleep..");
        sleep(4);
        puts("woke up");
        pthread_exit(0);
    }
    
    int main(int argc,char *argv[])
    {
        int i,n;
        puts("testing pkill");
        pthread_attr_t attr;
        pthread_t tid;
        //create child thread with default attributes
        pthread_attr_init(&attr);
        pthread_create(&tid,&attr,runner,0);
        pthread_cancel(tid);
        pthread_join(tid,NULL);//wait till finished
        //the parent process outputs value
        return 0;
    }
    

    Although not coinciding with the views above, the following code outputs

    testing pkill
    In the thread
    constructor called
    sleep..
    destructor called
    

提交回复
热议问题