3.5 线程的分离
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>void * callback(void * arg) {printf("chid thread id : %ld\n", pthread_self());return NULL;
}int main() {// 创建一个子线程pthread_t tid;//可以通过循环创建多个线程int ret = pthread_create(&tid, NULL, callback, NULL);if(ret != 0) {char * errstr = strerror(ret);printf("error1 : %s\n", errstr);}// 输出主线程和子线程的idprintf("tid : %ld, main thread id : %ld\n", tid, pthread_self());// 设置子线程分离,子线程分离后,子线程结束时对应的资源就不需要主线程释放ret = pthread_detach(tid);if(ret != 0) {char * errstr = strerror(ret);printf("error2 : %s\n", errstr);}// 设置分离后,对分离的子线程进行连接 pthread_join()会报错// ret = pthread_join(tid, NULL);// if(ret != 0) {// char * errstr = strerror(ret);// printf("error3 : %s\n", errstr);// }pthread_exit(NULL);return 0;
}
若设置分离后,对分离的子线程进行连接 pthread_join()会出现报错如下:
3.6线程取消
核心在于:取消线程后,不会立马终止该线程
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>void * callback(void * arg) {printf("chid thread id : %ld\n", pthread_self());for(int i = 0; i < 5; i++) {// sleep(1);printf("child : %d\n", i);}return NULL;
}int main() {// 创建一个子线程pthread_t tid;int ret = pthread_create(&tid, NULL, callback, NULL);if(ret != 0) {char * errstr = strerror(ret);printf("error1 : %s\n", errstr);}// 取消子线程,并非立马取消,而是遇到取消点(系统调用)才取消pthread_cancel(tid);for(int i = 0; i < 5; i++) {printf("%d\n", i);}// 输出主线程和子线程的idprintf("tid : %ld, main thread id : %ld\n", tid, pthread_self());pthread_exit(NULL);return 0;
}
3.7线程属性(pthread_attr_t)
命令查看线程属性pthread_attr_ 的相关函数:man pthread_attr_ 不要回车 按两次tab
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>void * callback(void * arg) {printf("chid thread id : %ld\n", pthread_self());return NULL;
}//通过线程属性设置线程分离
int main() {// 创建一个线程属性变量pthread_attr_t attr;// 初始化属性变量pthread_attr_init(&attr);// 设置属性(设置线程分离属性),要分离,但子线程结束后自己可以释放资源,不需要其他线程回收释放子线程的资源//默认是不分离:PTHREAD_CREATE_JOINABLE,可加入的pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);// 创建一个子线程pthread_t tid;int ret = pthread_create(&tid, &attr, callback, NULL);if(ret != 0) {char * errstr = strerror(ret);printf("error1 : %s\n", errstr);}// 获取线程的栈的大小size_t size;pthread_attr_getstacksize(&attr, &size);printf("thread stack size : %ld\n", size);// 输出主线程和子线程的idprintf("tid : %ld, main thread id : %ld\n", tid, pthread_self());// 释放线程属性资源pthread_attr_destroy(&attr);pthread_exit(NULL);return 0;
}
显示结果
默认分配线程栈的大小为8388608