面试题答案
一键面试思路
- 设置标志位:在主线程和目标线程共享的区域设置一个标志位,主线程通过修改这个标志位来通知目标线程需要终止。
- 线程检查标志位:目标线程在执行任务过程中,周期性地检查这个标志位。当发现标志位被设置时,开始准备终止。
- 资源释放:目标线程在终止前,负责释放其占用的资源,如关闭文件描述符等。
- 使用
pthread_join
等待线程结束:主线程使用pthread_join
函数等待目标线程完成资源释放并真正终止,确保线程安全退出。
关键代码示例
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
// 定义共享标志位
volatile int stop_thread = 0;
// 模拟大文件解析任务时打开的文件描述符
int file_descriptor;
// 线程执行的函数
void* complex_task(void* arg) {
// 模拟打开文件
file_descriptor = open("large_file.txt", O_RDONLY);
if (file_descriptor == -1) {
perror("open");
pthread_exit(NULL);
}
// 模拟复杂任务(解析大文件)
while (!stop_thread) {
// 实际解析文件的代码应该在这里,这里用简单输出模拟
printf("Parsing file...\n");
sleep(1);
}
// 释放资源
close(file_descriptor);
printf("Thread is terminating, file descriptor closed.\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread;
// 创建线程
if (pthread_create(&thread, NULL, complex_task, NULL) != 0) {
perror("pthread_create");
return 1;
}
// 主线程睡眠5秒后通知线程终止
sleep(5);
stop_thread = 1;
// 等待线程结束
if (pthread_join(thread, NULL) != 0) {
perror("pthread_join");
return 2;
}
printf("Main thread: Thread has been safely terminated.\n");
return 0;
}
在上述代码中:
stop_thread
是共享的标志位,volatile
关键字确保该变量的读写不会被编译器优化,保证线程间可见性。- 目标线程函数
complex_task
在执行任务过程中不断检查stop_thread
标志位,当标志位被设置时,关闭打开的文件描述符并退出。 - 主线程在睡眠5秒后设置
stop_thread
标志位,然后使用pthread_join
等待目标线程终止。