Linux-c 线程相关

Linux-c 线程相关

关于pthread_exit

结论

如果主线程使用 pthread_exit(rval) 那么主线程会等待所有的线程结束后才结束

代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

struct student{
    
    
        int age;
        char name[20];

};


void *thread_func(void *stu){
    
    
		sleep(1);
        printf("student age is %d, name is %s\n", ((struct student *)stu)->age, ((struct student *)stu)->name);
        return NULL;
  
}


int main(int argc, char *argv[]){
    
    

        pthread_t tid;
        int err;
        int *rval; 

        struct student stu;
        stu.age = 20;
        memcpy(stu.name, "James", 20);

        err = pthread_create(&tid, NULL, thread_func, (void *)(&stu));

        if(err != 0){
    
    
                printf("create new thread failed\n");
                return 0;
        }

        int i;
        printf("main thread have %d args\n", argc);

        for(i=0; i<argc; i++){
    
    
                printf("main thread args is %s\n", argv[i]);
        }

       pthread_exit(rval);


        return 0;
}

三种不同退出线程的方法比较

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *thread_func(void *arg){
    
    

        if(strcmp("1", (char *)arg) == 0){
    
    
                printf("new thread return! \n");
                return  (void *)1;
        }
        if(strcmp("2", (char *)arg) == 0){
    
    
                printf("new thread pthread_exit! \n");
                pthread_exit((void *)2);
        }
        if(strcmp("3", (char *)arg) == 0){
    
    
                printf("new thread exit! \n");
                exit(3);
        }
}


int main(int argc, int *argv[]){
    
    

        int err;
        pthread_t tid;

        err = pthread_create(&tid, NULL, thread_func, (void *)argv[1]);

        if(err != 0){
    
    
                printf("new thread failed\n");
                return 0;
        }

        sleep(1);

        printf("main thread\n");

        return 0;

}

运行结果

carey@ubuntu:~/thread$ ./thread_exit 
Segmentation fault (core dumped)
carey@ubuntu:~/thread$ ./thread_exit 1
new thread return! 
main thread
carey@ubuntu:~/thread$ ./thread_exit 2
new thread pthread_exit! 
main thread
carey@ubuntu:~/thread$ ./thread_exit 3
new thread exit! 
carey@ubuntu:~/thread$ 

结论

exit 会直接终止进程

而 return 和 pthread_exit((void *)2) 只是结束线程

猜你喜欢

转载自blog.csdn.net/qq_44861043/article/details/119547662