线程分离的作用:当主线程与新线程无关时,主线程无需等待新线程的结束。
1、进程属性初始化
pthread_attr_t pth_attr;
pthread_attr_init(&pth_attr);
2、进程分离属性设置。
pthread_attr_setdetachstate(&pth_attr,PTHREAD_CREATE_DETACHED);
3、进程创建。
4、进程属性资源回收。
pthread_attr_destroy(&pth_attr);
#include<stdio.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #include<pthread.h> void *thread_func(void *arg); #define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE);} while(0) char message[] = "hello Ruanchao!"; int finish=0; int main() { int res; pthread_t thread; pthread_attr_t pth_attr; res = pthread_attr_init(&pth_attr); if (res != 0) handle_error("pthread initial is failed!"); res = pthread_attr_setdetachstate(&pth_attr,PTHREAD_CREATE_DETACHED); if(res != 0) handle_error("pthread set attr failed!"); res = pthread_create(&thread,&pth_attr,thread_func,(void *)message); if(res != 0) handle_error("thread creation is failed!"); (void)pthread_attr_destroy(&pth_attr); while(!finish) { printf("Waiting for thread to end!\n"); sleep(1); } printf("thread were finished!\n"); exit("EXIT_FAILURE"); } void *thread_func(void *arg){ printf("thread_func is running,argument is %s\n",(char *)arg); sleep(5); finish = 1; pthread_exit(NULL); }
时间: 2024-12-17 15:57:41