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

后端 未结 4 1016
悲&欢浪女
悲&欢浪女 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<iostream>
    #include<pthread.h>
    
    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
    
    0 讨论(0)
  • 2021-01-02 02:28

    It's not standardised to do this. It appears that some implementations do and some don't.

    pthread_cancel() really should be avoided, if you can; it doesn't actually stop the thread until it hits a cancellation point, which is usually any other pthread_* call. In particular, on lots of platforms a cancel won't interrupt a blocking read.

    0 讨论(0)
  • 2021-01-02 02:49

    I doubt it - pthread is a pure C api, so I doubt it would have any mechanism to unwind the stack of the thread.

    0 讨论(0)
  • 2021-01-02 02:51

    The stack does not unwind when you 'kill' a thread.

    Killing threads is not a robust way to operate - resources they have open, such as files, remain open until the process closes. Furthermore, if they hold open any locks at the time you close them, the lock likely remains locked. Remember, you are likely calling a lot of platform code you do not control and you can't always see these things.

    The graceful robust way to close a thread is to interrupt it - typically it will poll to see if it's been told to close down periodically, or it's running a message loop and you send it a quit message.

    0 讨论(0)
提交回复
热议问题