结论:子线程不会因为主线程的退出而退出;如果进程没有退出的话子线程依然正常运转;如果进程退出了,那么它所有的线程都会退出,所以子线程也就退出了。

    1. # include<pthread.h>
    2. # include<unistd.h>
    3. # include<stdio.h>
    4. void* func(void* arg) {
    5. pthread_t main_tid = *static_cast<pthread_t*>(arg);
    6. sleep(6);
    7. pthread_cancel(main_tid);
    8. printf("main die \n");
    9. while (true)
    10. {
    11. printf("child loops\n");
    12. sleep(1);
    13. }
    14. return NULL;
    15. }
    16. int main() {
    17. pthread_t main_tid = pthread_self();
    18. pthread_t tid = 0;
    19. pthread_create(&tid, NULL, func, &main_tid);
    20. while (true) {
    21. printf("main loops\n");
    22. sleep(1);
    23. }
    24. sleep(10);
    25. printf("main exit \n");
    26. return 0;
    27. }