#include #include #include void clean(void *data) { printf("---已清理---\n"); } void *read_line(void *path) { pthread_cleanup_push(clean, NULL); // 注册清理函数 printf("按行读取 %s 数据\n", (char *)path); sleep(2); pthread_cleanup_pop(1); // 执行清理函数 } int main(int argc, char const **argv) { if (argc != 3) { printf("usage: %s filepath1 filepath2", argv[0]); return 0; } pthread_attr_t attr; // 线程属性 pthread_attr_init(&attr); // 初始化线程属性 // 设置线程分离 (通过属性修改) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // 获取当前线程的栈的大小 size_t stackSize; pthread_attr_getstacksize(&attr, &stackSize); printf("线程默认的栈大小: %ld Mb\n", stackSize / 1024 / 1024); stackSize /= 2; pthread_attr_setstacksize(&attr, stackSize); pthread_attr_getstacksize(&attr, &stackSize); printf("修改后栈大小: %ld Mb\n", stackSize / 1024 / 1024); // 获取当前线程的优先级 struct sched_param param; pthread_attr_getschedparam(&attr, ¶m); printf("默认线程的优先级: %d\n", param.__sched_priority); pthread_t tid2; pthread_create(&tid2, &attr, read_line, (void *)argv[2]); pthread_t tid; pthread_create(&tid, &attr, read_line, (void *)argv[1]); // 创建线程 param.__sched_priority = 10; // 设置单个线程的优先级 pthread_setschedparam(tid, SCHED_FIFO, ¶m); struct sched_param param2; param2.__sched_priority = 12; pthread_setschedparam(tid2, SCHED_FIFO, ¶m2); int detachstate; if (pthread_attr_getdetachstate(&attr, &detachstate) == 0) // 获取线程的分离状态 { if (detachstate != PTHREAD_CREATE_DETACHED) // 如果线程不是分离状态 { pthread_join(tid, NULL); // 等待线程结束 } } sleep(3); pthread_attr_destroy(&attr); // 清理线程属性 return 0; }